Angular:如何将类添加到子组件的嵌套元素

时间:2018-12-23 08:23:59

标签: css angular

我有一个作为输入+下拉列表DropdownSelect的组件,如何为该嵌套在下拉列表组件中的元素添加类?

输入+下拉HTML

<input class="number-input"
       #input
       [(ngModel)]="value.input"
       (ngModelChange)="onInputChange($event)"
       (blur)="onInputBlur()">
<app-dropdown-select [dropdownItems]="dropdownItems"
                     [(selectedItem)]="value.dropdownItem"
                     (selectedItemChange)="onDropdownChange($event)"
                     combinedInput="true"
                     class="dropdown-btn">
</app-dropdown-select>

DropdownSelect组件:

<div class="button-container">
  <div class="dropdown-button"
       (click)="onClick($event)"
       [class.dropdown-active]="showList && !combinedInput"
       [class.dropdown-input-active]="showList && combinedInput">
    <div class="downdown-selected-item">
      {{selectedItem?.name}} {{selectedItem?.unit}}
    </div>
    <span class="spacer"></span>
    <i class="material-icons">
      {{buttonIcon}}
    </i>
  </div>

  <div class="dropdown-items" *ngIf="showList">
    <div *ngFor="let item of dropdownItems"
         (click)="onClickItem(item)"
         class="dropdown-item">
      {{item.name}},
      {{item.description}}
    </div>
  </div>
</div>

我想将类invalid添加到类dropdown-button的元素中

我设法将类添加到组件,不知道如何添加到内部元素。

@ViewChild(DropdownSelectComponent, { read: ElementRef }) dropdownSelectComponent: ElementRef;

添加课程:

this.dropdownSelectComponent.nativeElement.classList.add('invalid');

1 个答案:

答案 0 :(得分:0)

有两种方法可以实现此目的,我将在下面说明。

如果要从外部组件有条件地应用无效类,您可以采用的一种方法是在compnents.ts文件中添加一个额外的@Input()变量,以传入您的组件,这样看起来喜欢:

<input class="number-input"
       #input
       [(ngModel)]="value.input"
       (ngModelChange)="onInputChange($event)"
       (blur)="onInputBlur()">
<app-dropdown-select [dropdownItems]="dropdownItems"
                     [(selectedItem)]="value.dropdownItem"
                     (selectedItemChange)="onDropdownChange($event)"
                     combinedInput="true"
                     [invalidInput]="{{condition}}"
                     class="dropdown-btn">
</app-dropdown-select>

然后,您可以在组件本身中添加一个[ngClass]绑定,以便内部组件最终看起来像这样:

...
<div class="dropdown-button"
       (click)="onClick($event)"
       [class.dropdown-active]="showList && !combinedInput"
       [class.dropdown-input-active]="showList && combinedInput"
       [ngClass]="{'invalid': invalidInput}">
    <div class="downdown-selected-item">
      {{selectedItem?.name}} {{selectedItem?.unit}}
    </div>
    <span class="spacer"></span>
    <i class="material-icons">
      {{buttonIcon}}
    </i>
...

有关ngClass角度绑定的更多信息,请点击此处https://angular.io/api/common/NgClass