簡體   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