【发布时间】:2020-01-21 12:18:40
【问题描述】:
我的应用程序nav.component 和list.component 中有两个独立的组件。主要思想是从nav.component 发送到list.component 并在list.component 中将该值添加到数组中。我读到有很多不同的方法可以实现这一目标。我尝试了 EventEmitter 但似乎我的方法不起作用。为什么?什么是正确的方法?
导航组件
nav.component.html:
<mat-form-field class="example-full-width">
<input matInput placeholder="Add" [(ngModel)]="value" >
</mat-form-field>
<div class="example-button-row">
<button mat-stroked-button (click)="sendMessage()">Add</button>
</div>
nav.component.ts:
import { Component, OnInit ,EventEmitter, Input, Output} from '@angular/core';
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
public value:string;
@Output() onAddItem = new EventEmitter<string>();
constructor() { }
ngOnInit() {
}
sendMessage() {
this.onAddItem.emit(this.value);
}
}
列表组件
list.component.html
<mat-list role="list">
<mat-list-item role="listitem" *ngFor="let product of Products">{{product}}</mat-list-item>
</mat-list>
list.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
public Products:string[] = ["one","two","Three","Four","Five"];
constructor() {
}
ngOnInit() {
}
onAddItem(item:string) {
this.Products.push(item);
}
}
【问题讨论】:
-
文档中有一整页是关于组件间交互的。 angular.io/guide/component-interaction
标签: angular