父組件向子組件傳值 @Input
文件目錄html
父組件:this
father.template.htmlspa
<h1>父組件</h1> <cmt-child [data]='data'></cmt-child>
father.component.ts3d
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'cmt-father', templateUrl: './father.template.html' }) export class FatherComponent implements OnInit { data: any = '我是傳往子組件的值' ngOnInit() { } ngOnChanges() { } }
子組件:(使用@Input修飾器去接收)code
childcomponent.tscomponent
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) } }
這樣就把值從父組件傳到了子組件!htm
子組件向父組件傳值(子組件經過方法藉助修飾器@output傳值給父組件)
子組件blog
childcomponent.tsit
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.htmlconsole
<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) } }
這樣子組件經過點擊就把值傳遞給了父組件!