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


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

父組件向子組件傳值   @Input

文件目錄

 

父組件:

father.template.html

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

father.component.ts

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

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

    ngOnChanges() {
    }

}

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

childcomponent.ts

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)
    }

}

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

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

子組件

childcomponent.ts

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.html

<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)
    }
}

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM