为了账号安全,请及时绑定邮箱和手机立即绑定

基于输入操作可重用组件

基于输入操作可重用组件

暮色呼如 2021-10-21 16:57:57
我创建了一个可重用的组件并在一个组件内使用它两次。但是我需要两个按钮,它们可以单独操作组件。在我的情况下,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。
查看完整描述

1 回答

?
跃然一笑

TA贡献1826条经验 获得超6个赞

您必须让服务知道您从哪个组件调用。


尝试我在演示中所做的更改。


应用程序组件.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() componentNumber: number;


 ngOnInit() {

    this.service.addFruit.subscribe((x) => {

      if (x == this.componentNumber)

        this.items.unshift({ fruit: 'Blackberry' });

    });

  }


查看完整回答
反对 回复 2021-10-21
  • 1 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信