我有一系列位于元素内部的输入框,我想让输入框的父元素根据鼠标聚焦的位置分别具有边框。代码如下所示:
HTML(只是输入元素之一,因为它们的编码方式相同):
<div class="parent-element">
<input type="text"
[class.bordered]="myBooleanVariable"
(focus)="addBorder()"
(blur)="removeBorder()"
/>
</div>
typescript :
addBorder() {
this.myBooleanVariable = true;
}
removeBorder(event) {
this.myBooleanVariable = false;
}
我遇到的问题是,当 bordered
类应用于 focus
时,所有 .parent-element
div 都得到边界,因为 myBooleanVariable
为 true 或 false。我想避免制作静态变量,如 myBooleanVariable1
、myBooleanVariable2
等。
我怎样才能做到这一点?
最佳答案
您可以使用 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');
}
}
关于angular - 如何在输入焦点上动态控制 Angular 2+ 中父元素的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50806805/