javascript - 根据输入操作可重用组件

标签 javascript angular

我创建了一个可重用的组件,并在组件内使用它两次。但我需要两个按钮,可以单独操作组件。

在我的例子中,component1 的按钮不应同时更新组件的实例。

我认为我在设计上做错了一些事情,但任何建议都会对我有帮助。

Stackblitz

可重用组件:-

    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);
}

reusable.component.ts:

@Input() 组件编号:数字;

 ngOnInit() {
    this.service.addFruit.subscribe((x) => {
      if (x == this.componentNumber)
        this.items.unshift({ fruit: 'Blackberry' });
    });
  }

<强> Working Stackbiltz

关于javascript - 根据输入操作可重用组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58004879/

相关文章:

Angular 2等待服务结果到来

javascript - 从文件路径或 url 获取目录

javascript - Knockout 嵌套绑定(bind)相互更新的问题,但不是 dom

javascript - Jest/ enzyme 测试没有给出预期的输出?

javascript - ESLint 双引号中的双引号

angularjs - Angular 2 npm 安装报错包

javascript - 如何更改此 d3.js 树中祖先文本的样式类和内容?

java - Spring boot Birt Report 与 Angular 2 客户端生成损坏的 PDF 文件

angular - 错误 : Initializers are not allowed in ambient contexts

angular - 如何在 Angular 2 中开发与 app 模块并行的多个模块?