为什么属性绑定到文本元素的颜色在angular中不起作用?



下面是我的。ts文件,

import { Component } from '@angular/core';
@Component({
selector: 'app-event-binding',
templateUrl: './event-binding.component.html',
styleUrls: ['./event-binding.component.css']
})
export class EventBindingComponent {
textColor = '';
onInput = (ev: any) => {
this.textColor = ev.target.value;
}
}
下面是我的HTML模板,
<div>
<h3 [style.color]="textColor">EVENT BINDING</h3>
<input type="text" (input)="onInput($event)">
</div>

这里当我完全键入"blue"在输入框中,我的文本颜色h3改为蓝色.但是我注意到当我按退格键时,现在textColor的值是" blue ",文字仍然是蓝色的。我还以为会变黑呢。只有当我清空所有输入时,它才会变成黑色。那么html中的颜色是否保留了一些历史呢?这是什么?

在使用纯JavaScript操作DOM时也会发生相同的情况,我为您准备了一个示例:

document.querySelector('input').addEventListener('input', event => {
document.querySelector('h3').style.color = event.target.value;
})
<h3>EVENT BINDING</h3>
<input type="text">

当尝试设置浏览器认为无效的值时,不执行该操作。您可以在DOM中看到,内联样式的值没有更新。在这种情况下,将使用最后一个有效的值。Angular在这里的工作原理与纯JavaScript相同。

作为一种解决方法,您可以检查输入的值是否与CSS.supports()有效,并返回到黑色:

onInput = (ev: any) => {
const value = ev.target.value;
this.textColor = CSS.supports('color', value) ? value : 'black';
}

最新更新