[英]Manipulating a reusable component based on input
我创建了一个可重用的组件,并在一个组件中使用了两次。 但我需要两个按钮,可以单独操作组件。
在我的情况下,component1 的按钮不应该同时更新组件的实例。
我认为我在设计上做错了什么,但任何建议都会对我有所帮助。
可重复使用的组件:-
import { Component, OnInit,Input } from '@angular/core';
import { AppService } from '../app.service';
@Component({
selector: 'app-reusable',
templateUrl: './reusable.component.html',
styleUrls: ['./reusable.component.css']
})
export class ReusableComponent implements OnInit {
@Input() items:any;
constructor(
private service:AppService
) { }
ngOnInit() {
this.service.addFruit.subscribe(()=>{
this.items.unshift({fruit:'Blackberry'});
});
}
}
用法:-
<button type="button" (click)="Add()">Add Component1</button>
<app-reusable [items]="fruitList1"></app-reusable>
<hr/>
<button type="button" (click)="Add()">Add Component2</button>
<app-reusable [items]="fruitList2"></app-reusable>
我想一次只更新一个可重用组件的实例。 实例 1 或 2。
您必须让服务知道您从哪个组件调用。
试试我在演示中所做的更改。
app.component.html
<button type="button" (click)="Add(1)">Add Component1</button>
<app-reusable [items]="fruitList1" [componentNumber]="1"></app-reusable>
app.component.ts:
Add(componentNumber:number){
this.service.addFruit.next(componentNumber);
}
可重用的.component.ts:
@Input() componentNumber: number;
ngOnInit() {
this.service.addFruit.subscribe((x) => {
if (x == this.componentNumber)
this.items.unshift({ fruit: 'Blackberry' });
});
}
更简洁的方法是简单地传递组件实例并调用相关方法,因此在可重用组件中创建一个方法,例如
addFruit(){
this.items.unshift({fruit:'Blackberry'});
}
修改您的 add 方法以获取组件作为实例并调用此方法
Add(instance:ReusableComponent){
instance.addFruit();
}
然后添加 hash 以分离每个实例并在方法中传递实例
<button type="button" (click)="Add(instance1)">Add Component1</button>
<app-reusable [items]="fruitList1" #instance1></app-reusable>
每个 ReusableComponent 实例都订阅了 Subject addFruit。 单击该按钮将更新主题值,这将触发所有订阅。
为了避免这种情况,您需要在订阅中添加一个过滤器,该过滤器通过在执行this.service.addFruit.next();
. 您可以使用 RXJS 过滤器运算符进行过滤。 https://rxjs-dev.firebaseapp.com/api/operators/filter
另一个想法是为服务中的每个组件创建订阅,并将它们保存在服务中的某个地图/对象中。 当组件向服务请求订阅时,它会向 map 添加一个条目,即 subjectId: new Subject()。 您将返回该新主题以供组件订阅。 您可以调用服务方法 addNewFruit(subjectId: string, newFruit: string): void,而不是直接执行 next()。 Map 将是:
{
'firstId': Subject,
'secondId': Subject,
}
对于这种情况,最简单的想法是使用 ViewChild 并从父组件调用方法 addFruit。
与其在可重用组件中订阅 APP 服务,不如在单击按钮时修改提供给组件的输入。 如果您一次更新fruitList1 或fruitList2,那么它不会更新该组件的另一个实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.