【问题标题】:Connecting HTML select options with two way binding Angular2+使用两种方式绑定 Angular2+ 连接 HTML 选择选项
【发布时间】:2020-04-17 03:19:26
【问题描述】:

我正在我的应用程序中创建一个功能来改变我在 Angular 中工具栏的颜色。

为此,我创建了一个具有颜色字符串参数的指令。

当我硬编码我想要的值时,该指令可以正常工作,

现在我想使用一个选择选项将值动态分配给指令。

我目前正在通过点击事件这样做。我的方法是从选项中收集我的值并将其分配给我的 toolBarColor 变量的值。

我通过检查发现我的方法成功地收集了值并将其分配给连接到我的指令的变量。

我也尝试过 [ngValue] 和 ngModel 路线,但还没有成功。

下面是我的代码。

<select class="form-control" (click)="colorSelect(colorChosen)" [(ngModel)]="toolbarColor">
  <option *ngFor="let color of themeColors" value="{{color}}">{{color}}</option>
</select>

我的组件包含这个方法

colorSelect(color: string){
    this.toolbarColor = color;
  }

toolbar 只是一个空字符串变量。

指令代码就是这样。

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}}>

【问题讨论】:

  • 您需要提供更多与指令相关的代码,能否为您的代码创建一个基本的 stackblitz 实例?
  • 遗憾的是 stackblitz 在生成 repo 实例时遇到问题。说它缺少我的 package.json 文件,这是一个错误,因为它存在于 repo 中。我会将我的指令代码添加到初始问题中。
  • 能否请您添加代码,您在模板中如何以及在何处使用此指令?
  • 我刚刚插入。

标签: angular html-select angular-directive two-way-binding


【解决方案1】:

当您的指令的输入发生更改时,您并没有更新背景。有两种可能的解决方案。

1.使用带有如下支持变量的 setter:

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;
  }
}

2。像这样使用 ngOnChanges 事件:

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;
  }
}

【讨论】:

  • 你是对的,变化只发生在 onInit 而不是 onChanges。我试图在组件而不是指令中添加 onChanges 方法。格雷西!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
  • 1970-01-01
  • 2015-04-03
  • 2017-02-06
相关资源
最近更新 更多