英文:
How to change the background color of input field when a button is clicked?
问题
我想在单击按钮时将输入字段更改为更改颜色。额外信息:单击按钮时按钮的值本身也会更改。
这是我现在拥有的HTML:
<h2 class="label-custom">Tag</h2>
<input class="input" [readonly]="isReadOnly" formControlName="tag" [placeholder]="'Enter your tags' | transloco">
<button type="alter-button" class="alter-button" (click)="alter()">{{btnVal}}</button>
alter()函数的作用是使字段只读并更改按钮名称。我还可以根据btnVal当前包含的值更改输入字段的背景颜色,因为alter()函数在每次单击时都会调用。是否有办法在包含alter()函数的TypeScript文件中更改输入字段的背景色?
英文:
I would like to change my input field to change color when I click on a button. For extra information: the button's value itself changes when it is clicked.
This is the HTML I have right now:
<h2 class="label-custom">Tag</h2>
<input class="input" [readonly]="isReadOnly" formControlName="tag" [placeholder]="'Enter your tags' | transloco">
<button type="alter-button" class="alter-button" (click)="alter()">{{btnVal}}</button>
All the alter() function does is make the field readonly and change the button name. I can also change the color of the input field depending on what value the btnVal currently holds since the alter() function is called with each click. Is there a way I can change the background of the input field within the typescript file containing the alter() function?
答案1
得分: 0
你可以将alter()
函数修改为如下内容:
import { Component, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h2 class="label-custom">Tag</h2>
<input class="input" [readonly]="isReadOnly" formControlName="tag" [placeholder]="'Enter your tags' | transloco">
<button type="alter-button" class="alter-button" (click)="alter()">{{btnVal}}</button>
`
})
export class AppComponent {
isReadOnly = false;
btnVal = 'Alter';
constructor(private elementRef: ElementRef) {}
alter() {
this.isReadOnly = !this.isReadOnly;
this.btnVal = this.isReadOnly ? 'Revert' : 'Alter';
const inputElement = this.elementRef.nativeElement.querySelector('.input');
inputElement.style.backgroundColor = this.isReadOnly ? 'lightgray' : 'white';
}
}
英文:
You can modify the alter()
function to something like this
import { Component, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h2 class="label-custom">Tag</h2>
<input class="input" [readonly]="isReadOnly" formControlName="tag" [placeholder]="'Enter your tags' | transloco">
<button type="alter-button" class="alter-button" (click)="alter()">{{btnVal}}</button>
`
})
export class AppComponent {
isReadOnly = false;
btnVal = 'Alter';
constructor(private elementRef: ElementRef) {}
alter() {
this.isReadOnly = !this.isReadOnly;
this.btnVal = this.isReadOnly ? 'Revert' : 'Alter';
const inputElement = this.elementRef.nativeElement.querySelector('.input');
inputElement.style.backgroundColor = this.isReadOnly ? 'lightgray' : 'white';
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论