繁体   English   中英

Angular2动态获取组件引用

[英]Angular2 Get component reference dynamically

我的应用程序中生成了多个<mat-button-toggle>元素,我希望始终只选择一个。 我现在遇到的问题是,当单击另一个切换按钮时,如何获取对上一个选定切换按钮的组件引用。

我确实搜索了很长时间,但不知道该怎么做。

component.html

<mat-button-toggle (click)="onKeywordSelect($event)" *ngFor="let keyword of keywords" [id]="keyword.id" [attr.id]="keyword.id" [value]="keyword.id" class="keyword">
  <div class="text">{{ keyword.name }}</div>
</mat-button-toggle>

component.ts

// imports and @Component

export class NavbarComponent implements OnInit {

  keywords = [new Keyword('name1'), new Keyword('name2')]; // sample data
  $selectedKeyword: $ | any; // I've imported JQuery

  onKeywordSelect(event: any) {
    // This element depends on where you mouse was positioned when clicking
    // Most often not the <mat-button-toggle> but some child element
    const target = event.target;
    // To get to the <mat-button-toggle> component that was clicked
    const matButton = $(target).closest('mat-button-toggle');

    if (this.$selectedKeyword !== undefined) {
        // At the start there is no selected keyword
        // TODO: Set the 'checked' property of the cur selected keyword to false
    }
    this.$selectedKeyword = $matButton;
  }
}

我尝试使用@ViewChild()进行操作,但是由于当用户选择一个关键字时,所选关键字的id更改,因此我不知道如何跟踪所选组件的引用。

编辑

忘了提:是的,我知道mat-button-toggle-group但是由于某些样式,我不想使用它。 有没有其他方法可以解决这个问题?

编辑:更新了我的ans,因为您的要求是不使用mat-button-toggle-group

您可以使用checked属性并在change事件上设置当前和上次选择的值,如下所示:

component.html:

<mat-button-toggle
  *ngFor="let keyword of keywords"
  value="{{keyword.id}}"
  [id]="keyword.id"
  [attr.id]="keyword.id"
  (change)="this.onChange(keyword.id)"
  [checked]="this.currValue === keyword.id">
  {{keyword.name}}
</mat-button-toggle>

<div class="example-selected-value">
    Last Selected value: {{this.lastValue}}
</div>
<div class="example-selected-value">
    Current Selected value: {{this.currValue}}
</div>

component.ts:

keywords: any = [
    {id: 1, name: "name1"},
    {id: 2, name: "name2"},
    {id: 3, name: "name3"},
  ]
  lastValue: string = "";
  currValue: string = "";

  onChange = (value) => {
    this.lastValue = this.currValue;
    this.currValue = value;
  }

在此处检查演示。

 Add mat-button-toggle-group to select only one button and get value of group to get last selected button see: https://stackblitz.com/angular/yrqebgjbxao?file=app%2Fbutton-toggle-exclusive-example.ts 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM