将 Angular4 中的 [ngStyle] 绑定到 ngModel 或 2 种方式绑定

Binding [ngStyle] in Angular4 to ngModel or 2 way binding

我正在尝试制作一个输入框并为其添加颜色。段落的背景应添加相同的颜色。我正在尝试但出现错误。有人可以帮忙吗?

home.html

<input type="text" [(ngModel)]="colorName"/>
<p [ngStyle]="{background-color:'colorName'}">This is a paragraph.</p>

home.ts

  colorName: string = 'red';

Note: I want to do this with [ngStyle] and 2-way binding only in Angular4

只需删除 colorName 中的引号并在 css 属性 中添加引号,就像这样 -

<input type="text" [(ngModel)]="colorName"/>
<p [ngStyle]="{'background-color':colorName}">This is a paragraph.</p>

Working Example

这样做:

<p [ngStyle]="{'background-color':colorName}">This is a paragraph.</p>

您可以在 background-color

中添加 ''
<input type="text" [(ngModel)]="colorName"/>
<p [ngStyle]="{'background-color':colorName}">This is a paragraph.</p>