【问题标题】:How to make changes to other components with same name without affecting the current component如何在不影响当前组件的情况下更改其他同名组件
【发布时间】:2019-03-15 05:57:35
【问题描述】:

在我的用户组件中,我使用 4 个用户数据组件来为用户显示 4 个不同的数据。现在,在我的用户数据组件内部有一个 div,只有当局部变量 isEdit 为 true 时才可见。现在何时,用户数据上的 div 可见,另一个不可见。我该怎么做,即一旦一个 div 可见,所有其他 div 应该隐藏在其他组件中而不影响当前组件?

<div class="user-detail" >
 <div class="user-action" *ngIf="isEdit">
 <label>Aeshna <i (click)="add()" class="fas fa-times"></i></label>
 <div>
    <i (click)="selected()" class="fas fa-plus-square"></i>
    <p>Add user</p> 
 </div>
</div>

 <img (click)="click()" [ngStyle]="{'width': width}" src="../../../../assets/images/user/{{orientation}}/{{user}}.svg">
</div>

这是我的用户详细信息。click() 函数使 isEdit 为真

【问题讨论】:

  • 一次只能看到一个 div 吗?
  • 是的..在所有 4 个组件中都有一个图像,单击它会显示我正在使用 isEdit 的 div。但问题是,isEdit 对于其他 3 个组件没有改变,因此它们仍然可见
  • 你能提供一点代码吗?
  • 所以每次图片点击都应该显示对应的div?
  • 看起来您需要为所有用户数据组件提供服务,该组件维护一个变量(4 个数组),指示哪些组件应该是可见的。

标签: angular


【解决方案1】:

您在单击/事件时创建一个 rxjs 主题。发送活动的 id 并创建一个或多个观察者来监听它,并且该功能保持该特定 id 打开并关闭其余部分(或您想要的任何逻辑)或每个项目都为自己和行为个体进行监听

【讨论】:

    【解决方案2】:

    您可以通过创建消息服务来归档它

    这里是例子

    消息服务:

    import { Observable, Subject } from 'rxjs';
    @Injectable({
      providedIn: 'root'
    })
    export class FlagService {
    getFlag() : Observable<any> {
      return this.subject.asObservable();
    }
    setFlag(result:Code){
      this.subject.next({ text: code });
    }
    

    为 isEdit 设置标志的组件

    export class componentOne OnInit {
    constructor(private service: FlagService ){}
    sendDataToMessageService(){
      this.isEdit = true; // this need to be dynamically changed based on your condition
      this.service.setFlag(this.isEdit);
    }
    

    你使用了 4 次的组件

    export class otherComponent OnInit {
    constructor(private service: FlagService ){}
    ngOnInit(){
       this.service.getFlag().subscribe(response => {
        this.isEdit = response // here you can get updated data of your variable isEdit from the component where you set the isEdit value 
     });
    

    }

    希望对你有帮助

    【讨论】:

    • 所有 4 个组件都相同没有不同。我在用户组件中使用了相同的组件 4 次
    • 所以基本上你有 2 个组件,其中 isEdit 正在更改的组件和您想要获取 isEdit 数据的其他组件,对吗?
    • ya 2 个组件。在第一个组件内,我使用了第二个组件 4 次。因此,如果 isEdit 对 4 个相同组件之一为真,则对所有其他组件应该为假
    • 好的,所以你需要实现我已经在答案部分编写的消息服务,但是这个代码你需要在你使用 4 次的组件中编写(ngOnInit(){ this.service. getFlag().subscribe(response => { this.isEdit = response // 在这里您可以从设置 isEdit 值的组件中获取变量 isEdit 的更新数据 });)
    • 但我将 isEdit 设置在同一个组件中,我将从哪里调用 getFlag()
    猜你喜欢
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多