angular4父組件向子組件傳值,子組件向父組件傳值的方法

歡迎加入前端交流羣交流知識獲取視頻資料:749539640

父組件向子組件傳值   @Input

文件目錄html

 

父組件:前端

father.template.htmlthis

<h1>父組件</h1>
<cmt-child [data]='data'></cmt-child>

father.component.tsspa

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'cmt-father',
    templateUrl: './father.template.html'
})
export class FatherComponent implements OnInit {
    data: any = '我是傳往子組件的值'
    ngOnInit() {
    }

    ngOnChanges() {
    }

}

子組件:(使用@Input修飾器去接收)3d

childcomponent.tscode

import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'cmt-child',
    templateUrl: './child.template.html'
})
export class ChildComponent implements OnInit {
    @Input() data: any;//接收父組件的值
    ngOnInit() {
        console.log(this.data)
    }

    ngOnChanges() {
        console.log(this.data)
    }

}

這樣就把值從父組件傳到了子組件!component

子組件向父組件傳值(子組件經過方法藉助修飾器@output傳值給父組件)

子組件視頻

childcomponent.tshtm

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
    selector: 'cmt-child',
    templateUrl: './child.template.html'
})
export class ChildComponent implements OnInit {
    @Output('checked') checkedBack = new EventEmitter<any>();
    id:any ="我是傳給父組件的值"
    ngOnInit() {
    }

    ngOnChanges() {
    }
    checkedCallback() {
        this.checkedBack.emit(this.id);
    }
}

child.template.html.htmlblog

<h1>子組件</h1>
<button (click)='checkedCallback()'>點擊傳值給父組件</button>

父組件

father.template.html

<h1>父組件</h1>
<cmt-child (checked)="checkedBack($event)"></cmt-child>

father.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'cmt-father',
    templateUrl: './father.template.html'
})
export class FatherComponent implements OnInit {
    ngOnInit() {
    }

    ngOnChanges() {
    }
    
    checkedBack(event) {
        console.log(event)
    }
}

這樣子組件經過點擊就把值傳遞給了父組件!

相關文章
相關標籤/搜索