[英]Why @Input() in angular 4 behaving like two way data binding not one-way?
據我所知輸入是一種溝通方式。 對子組件中的@Input()變量所做的任何更改都不會反映在父組件中。
我在 app 組件中有一個空數組。 App 組件有兩個子組件。 一個是表單組件(添加新條目) ,第二個是列表組件(顯示所有條目) 。 在 Input 的幫助下,該空數組被傳遞給 form comp。 但是表單組件內部 Input() 數組的變化也反映在根組件中。 並且列表組件得到更新。 這是代碼:
app.component.ts
@Component({
selector: 'app-root',
template: `<div>
<app-form [formElements]="serverElements"> </app-form>
<app-list *ngFor = "let server of serverElements" [listServer]="server">
<app-list>
</div>`
})
export class AppComponent {
serverElements = [];
}
app-form.component.html
<div class="row">
<div class="col-xs-12">
<p>Add new Servers or blueprints!</p>
<label>Server Name</label>
<input type="text" class="form-control" [(ngModel)]="newServerName">
<label>Server Content</label>
<input type="text" class="form-control" [(ngModel)]="newServerContent">
<br>
<button
class="btn btn-primary"
(click)="onAdd()">Add Server</button>
</div>
</div>
app-form.component.ts
export class FormComponent {
@Input() Elements=[];
newServerName = '';
newServerContent = '';
constructor() { }
onAdd() {
this.Elements.push({
name: this.newServerName,
content: this.newServerContent
});
}
}
app-list.component.ts
@Component({
selector: 'app-server-element',
template: ` <div class="panel-heading">{{ server.name }}</div>
<div class="panel-body">
<p>{{server.content}}</p>
</div>`,
})
export class ListComponent implements {
@Input() server;
constructor() { }
}
我是這樣解決的,但剩下的只是為我做更多的測試和學習。
角 V.9.1.0
export class AppComponent implements OnInit {
@Input() public api: ApiModule; //ApiModule is a interface.
@Input() public titulo = '';
constructor(private router: Router, private dataService: DataService) {
}
ngOnInit() {
setTimeout(() => {
this.dataService.apiModule = this.api;
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.