[英]How to have a different instance of a component in angular
I have a parent component and a child component.我有一个父组件和一个子组件。 Here is the html from the parent.这是来自父级的 html。 To summarize总结一下
parent.html父.html
<child-component [(ngModel)]="model1"></child-component> //#1
<child-component [(ngModel)]="model2"></child-component> //#2
<child-component [(ngModel)]="model3"></child-component> //#3
<child-component [(ngModel)]="model4"></child-component> //#4
<button (click)="removeInput()">Remove #3</button>
parent.ts父母.ts
@Component({
templateUrl: './parent.component.html',
styleUrls: ['./parent.css']
})
export class ParentComponent implements OnInit {
@ViewChild(ChildComponent, {static: false}) childInteractor: ChildComponent;
removeInput()
{
this.childInteractor.value = "";
}
}
What should I do to make the child component declared in the parent are different instances?我应该怎么做才能使父组件中声明的子组件成为不同的实例? because clicking the button removes #1 instead of #3因为单击按钮会删除 #1 而不是 #3
child.html孩子.html
<input type="text" [(ngModel)]="value">
child.ts child.ts
@Component({
selector: 'child-component',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
value: any;
}
You are using the same 'model' attribute as ngModel您正在使用与 ngModel 相同的“模型”属性
<child-component [(ngModel)]="model"></child-component>
this 'model' is the same in all 4 children.这个“模型”在所有 4 个孩子身上都是一样的。
please use an array or something, like model[1], model [2]... etc请使用数组或其他东西,例如模型 [1]、模型 [2]...等
So... the problem is, you overwrite values in one component, when updating in the sibling, is it correct?所以......问题是,你在一个组件中覆盖值,在兄弟组件中更新时,是否正确? then what you have to do is not have same input and output in different child-component那么你要做的就是在不同的子组件中没有相同的输入和输出
<child-component [(ngModel)]="model1"></child-component>
<child-component [(ngModel)]="model2"></child-component>
<child-component [(ngModel)]="model3"></child-component>
<child-component [(ngModel)]="model4"></child-component>
You should probably read about ngmodel, input and outputs to undersand your own code您可能应该阅读有关 ngmodel、输入和输出的信息以了解您自己的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.