如何在输入焦点上动态控制Angular 2+中父元素的类?

Moo*_*ose 2 angular2-template angular2-routing angular

我有一系列位于元素内部的输入框,我想让输入框的父元素根据鼠标的聚焦位置单独设置一个边框。代码如下所示:

HTML(只是输入元素之一,因为它们都以相同的方式编码):

<div class="parent-element">
  <input type="text"
    [class.bordered]="myBooleanVariable"
    (focus)="addBorder()"
    (blur)="removeBorder()"
  />
</div>
Run Code Online (Sandbox Code Playgroud)

打字稿:

addBorder() {
  this.myBooleanVariable = true;
}

removeBorder(event) {
  this.myBooleanVariable = false;
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,当在bordered上应用该类时focus,所有.parent-elementdiv 都会获得边框,因为myBooleanVariable它要么是 true,要么是 false。我希望避免静态变量一样myBooleanVariable1myBooleanVariable2

我怎样才能做到这一点?

izm*_*dev 6

您可以使用 JS 从组件方法中添加和删除类,为此,它为您的包装器创建一个模板变量并将此变量粘贴到方法参数中,在您获得包装器的 HTMLElement 的方法中

@Component({
  selector: 'my-app',
  template: `
    <div class="parent-element" *ngFor="let i of items" #wrap>
      <input type="text"
        (focus)="addBorder(wrap)"
        (blur)="removeBorder(wrap)"
      />
    </div>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  items = [1,2,3];

  addBorder(wrap: HTMLElement) {
    wrap.classList.add('bordered');
  }

  removeBorder(wrap: HTMLElement) {
    wrap.classList.remove('bordered');
  }
}
Run Code Online (Sandbox Code Playgroud)