@Input()父----->子
@Output()子----->父
代码部分
父组件:
<app-dialog [item]="currentItem" (newItemEvent)="addItem($event)"></app-dialog>
<hr />
<p>Parent组件</p>
<ul>
<li *ngFor="let item of items">{{item}}</li>
</ul>
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
//发送给儿子的值
currentItem = 'Television';
//父亲接受的值
items = ['默认值'];
addItem(newItem: string) {
this.items.push(newItem);
}
}
子组件:
<p>Child组件</p>
<p>
Today's item: {{item}}
</p>
<hr />
<label for="item-input">Add an item:</label>
<input type="text" id="item-input" #newItem>
<button (click)="addNewItem(newItem.value)">Add to parent's list</button>
import { Component, Input, OnInit, Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.scss']
})
export class DialogComponent implements OnInit {
constructor() { }
//父亲给儿子的值
@Input() item = ''; // decorate the property with @Input()
//发送给父亲的值
@Output() newItemEvent = new EventEmitter<string>();
addNewItem(value: string) {
this.newItemEvent.emit(value);
}
ngOnInit(): void {
console.log(this.item)
}
}
效果图:
最后讲一个坑:如果要使用ngModel指令的话需要在app.module文件引入 imports: [ BrowserModule, FormsModule ]