文件目錄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
子組件視頻
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) } }
這樣子組件經過點擊就把值傳遞給了父組件!