使用双向绑定Angular2连接HTML选择选项+
我正在我的应用程序中制作一个功能,可以改变我工具栏的颜色 为此,我创建了一个具有参数color string的指令 当我硬编码所需的值时,指令工作正常 现在,我想使用一个select选项来动态地将值分配给指令 我这样做,目前通过点击事件。我的方法是从选项中收集我的值,并将其指定给我的工具栏颜色变量的值 我已经通过检查进行了检查,发现我的方法成功地收集了值,并将其分配给连接到我的指令的变量 我也尝试过[ngValue]和ngModel路线,但还没有成功 下面是我的代码使用双向绑定Angular2连接HTML选择选项+,angular,html-select,angular-directive,two-way-binding,Angular,Html Select,Angular Directive,Two Way Binding,我正在我的应用程序中制作一个功能,可以改变我工具栏的颜色 为此,我创建了一个具有参数color string的指令 当我硬编码所需的值时,指令工作正常 现在,我想使用一个select选项来动态地将值分配给指令 我这样做,目前通过点击事件。我的方法是从选项中收集我的值,并将其指定给我的工具栏颜色变量的值 我已经通过检查进行了检查,发现我的方法成功地收集了值,并将其分配给连接到我的指令的变量 我也尝试过[ngValue]和ngModel路线,但还没有成功 下面是我的代码 <select cla
<select class="form-control" (click)="colorSelect(colorChosen)" [(ngModel)]="toolbarColor">
<option *ngFor="let color of themeColors" value="{{color}}">{{color}}</option>
</select>
工具栏只是一个空字符串变量
指令代码就是这样
import { Directive, AfterViewInit, Input, ElementRef } from '@angular/core';
@Directive({
selector: '[myColorPicker]'
})
export class ColorPickerDirective implements AfterViewInit {
@Input() myColorPicker: string;
constructor(private elRef: ElementRef) {
}
ngAfterViewInit(): void {
this.elRef.nativeElement.style.background = this.myColorPicker;
}
}
这是我的工具栏中指令的实现
<div class="toolbar" role="banner" myColorPicker={{toolbarColor}}>
当指令的输入更改时,您没有更新背景。有两种可能的解决办法 一,。使用具有支持变量的setter,如下所示: 二,。使用ngOnChanges事件,如下所示:
您需要提供更多与指令相关的代码,能否为您的代码创建一个基本stackblitz实例?遗憾的是,stackblitz在生成repo实例时遇到问题。说它缺少my package.json文件,这是一个bug,因为它存在于repo中。我将在第一个问题中添加我的指令代码。您能否也添加代码?您在模板中如何以及在何处使用此指令?我刚刚插入了它。您是对的,更改只发生在一次,而不是一次更改。我尝试在组件中而不是在指令中添加onChanges方法。格蕾西!
<div class="toolbar" role="banner" myColorPicker={{toolbarColor}}>
import { Directive, AfterViewInit, Input, ElementRef } from '@angular/core';
@Directive({
selector: '[myColorPicker]'
})
export class ColorPickerDirective implements AfterViewInit {
@Input()
set myColorPicker(val: string) {
this._myColorPicker = val;
updateBackground();
}
_myColorPicker!: string;
constructor(private elRef: ElementRef) {
}
ngAfterViewInit(): void {
updateBackground();
}
updateBackground() {
this.elRef.nativeElement.style.background = this._myColorPicker;
}
}
import { Directive, AfterViewInit, Input, ElementRef } from '@angular/core';
@Directive({
selector: '[myColorPicker]'
})
export class ColorPickerDirective implements AfterViewInit, OnChanges {
@Input() myColorPicker: string;
constructor(private elRef: ElementRef) {
}
ngAfterViewInit(): void {
updateBackground();
}
ngOnChanges(changes: SimpleChanges) {
updateBakground(); // I am not sure if myColorPicker contains the new value at this point. If not you need to read the new value from the changes object
}
updateBackground() {
this.elRef.nativeElement.style.background = this.myColorPicker;
}
}