直接使用 ng g component 的命令建立組件,會自動生成組件所需的文件,方便快捷。css
// 父組件 ng g component parent // 子組件 ng g component parent/child
@Input:將父做用域中的值「輸入」到子做用域中,以後子做用域進行相關處理html
@Output:子做用域觸發事件執行響應函數,而響應函數方法體則位於父做用域中,至關於將事件「輸出」到父做用域中,在父做用域中處理。Output通常都是一個EventEmitter的實例,使用實例的emit方法將參數emit到父組件中,觸發父組件中對應的事件。vue
使用 @Input()
讓子組件知道哪一個是輸入的屬性,對應vue中的props。app
父組件:函數
//parent.component.html
<div class="parent-style"> <h1>我是父組件</h1> <app-child [sendMsg]="msg"></app-child> //sendMsg任意命名 </div>
//parent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { public msg:string = '我是父組件傳遞過來的數據'; //須要傳遞的數據 constructor() { } ngOnInit() { } }
子組件:this
//child.component.html
<div class="child-style"> <h3>我是子組件</h3> <p>{{sendMsg}}</p> //查看頁面數據是否顯示? </div>
//child.component.ts
import { Component, OnInit ,Input} from '@angular/core'; //引入Input
@Component({
selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { @Input() sendMsg:string; //告訴組件,sendMsg是父組件傳進來的數據 constructor() { } ngOnInit() { } }
子組件:spa
//child.component.html <div class="child-style"> <button type="button" (click)="send()">點擊觸發</button> </div> //child.component.ts import { Component, OnInit ,Output,EventEmitter} from '@angular/core';//引入Output @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { @Output() private outer = new EventEmitter(); //輸出屬性,須要定義成事件 public info = "子組件消息"; constructor() { } ngOnInit() { } send(){ this.outer.emit(this.info);//經過emit將信息發射出去 } }
父組件:code
//parent.component.html <div class="parent-style"> <app-child (outer)="getData($event)"></app-child>//事件綁定獲取數據 <p>{{msg}}</p> </div> //parent.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { msg:string; constructor() { } ngOnInit() { } getData(data){ this.msg = data; } }