Angular2动态获取组件参考

时间:2018-09-04 12:29:56

标签: javascript angular

我在我的应用程序中生成了多个<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,但是由于某些样式,我不想使用它。没有其他方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

编辑:更新了我的答案,因为您的要求是不要使用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;
  }

检查演示Here

答案 1 :(得分:0)

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