我有两个组件,一个是Post:
import {Component} from '@angular/core';
@Component({
selector: 'post',
template: `
<h1>{{title}}</h1>
<p>{{postText}}</p>
<ul>
<li *ngFor="let postData of posts">
<news-feed></news-feed>
</li>
</ul>
`
})
export class Post {
title : string;
postText : string;
posts = [{title:"Post1",postText:"Wow greate post"}, {title:"Post1",postText:"Wow greate post"}]
constructor(title:string, postText:string) {
this.title = title;
this.postText = postText;
}
}
另一个是新闻源:
import {Component} from '@angular/core';
@Component({
selector: 'news-feed',
template: `
<h1>News Feed</h1>
<div class="radios">
<div class="form-check form-check-inline">
<label class="form-check-label">
<input class="form-check-input" type="radio" value="success" [(ngModel)]="commandResult.type (change)="getCommandResult()"> Succeeded
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input class="form-check-input" type="radio" value="fail [(ngModel)]="commandResult.type (change)="getCommandResult()"> Failed
</label>
</div>
</div>`
})
export class NewsFeed {
commandResult: any = {
type: 'fail'
};
constructor() {
}
getCommandResult() {}
}
我在post组件中重复新闻提要组件,当我更改其中一个重复组件中的单选按钮时,我发现它在所有重复组件中都会发生变化。也许我正在以错误的方式接近这个,因为我是ang2的新手。任何帮助表示赞赏。 In this link, I think I am facing similar issue, I know its angular1 but still the same issue.
答案 0 :(得分:0)
在父组件类中:
export class Post {
title : string;
postText : string;
posts = [{type:1, title:"Post1",postText:"Wow greate post"}, {type: 0, title:"Post1",postText:"Wow greate post"}]
....
父模板:
<li *ngFor="let postData of posts">
<news-feed [commandResult]=postData></news-feed>
</li>
在子组件类中:
import{Input) from "@angular/core"
export class NewsFeed {
@Input() commandResult: any ;
.......
setCommandResult(value): void {
this.commandResult.type = value;
}
}
并且
{{ commandResult.title }}
<input type="radio" (change)="setCommandResult(1)" [value]="1" [checked]="commandResult.type===1">Succeeded
<input type="radio" (change)="setCommandResult(2)" [value]="2" [checked]="commandResult.type===2">Failed
here阅读