代码之家  ›  专栏  ›  技术社区  ›  Maurice

如何访问用于*ngif指令的角材料组件的值?

  •  0
  • Maurice  · 技术社区  · 6 年前

    我有这个垫子切换组:

    <mat-button-toggle-group #group="matButtonToggleGroup">
      <mat-button-toggle value="specific">
          Specific
        </mat-button-toggle>
        <mat-button-toggle value="general" checked>
            General
          </mat-button-toggle>                
    </mat-button-toggle-group>
    

    我有这两个领域。

    <div *ngIf="group.value == specific">
    <mat-form-field id="id">
      <input matInput placeholder="Insert seed Id">
    </mat-form-field>
    <mat-form-field id="id">
          <input matInput placeholder="Insert affiliate rank">
        </mat-form-field>
      </div>
    

    正如您在第二个代码片段中看到的,我正试图仅在选择了特定的字段后在DOM中包含这些字段。但是这不起作用。我在这里读过 How to access Angular 2 template variable in ngIf 模板变量在template元素之外不可访问,我应该使用 @ViewChild 相反。我找到了关于如何使用ViewChild的教程 https://blog.angular-university.io/angular-viewchild/ . 但是它涉及到一个由用户自己制作的组件(colorsamplecomponent)。我试图引用我的buttongToggleGroup,如下所示:

      @ViewChild(matButtonToggleGroup)
        group: matButtonToggleGroup;
    

    但它不起作用,因为我不能导入MatButtonToggleGroup,我只能导入模块,但这不是一回事。

    有人能给我一些关于如何获取在ngif指令中使用的togglegroup的值的指针吗?谢谢你

    1 回复  |  直到 6 年前
        1
  •  1
  •   gizmo    6 年前

    你可以简单地使用 NgModel 这里有双向绑定:

    <mat-button-toggle-group [(ngModel)]="toggleValue" #group="matButtonToggleGroup">
    <...>
    <div *ngIf="toggleValue === 'specific'">
    

    当然,还要定义 toggleValue :

    export class YourComponent {
    
    toggleValue;