无法在 Angular6 的输入属性中提供空间作为值



>我正在尝试创建这样的泛型控件

动态控制.ts

import { Component, Input } from '@angular/core';
@Component({
  selector: 'ngo-button',
  template: `<button [ngClass]=class type={{type}}>{{message}}</button>`,
  styles: [`.one{border:solid 2px yellow} .two{background-color:pink} .three{
  background-color: blue;
}`]
})
export class HelloComponent  {
   @Input() type: string = 'button';
  @Input() class: string = 'one three';
  @Input() message: string = 'submit';
}

主要组件.html

<ngo-button [class]='btn two' (click)='somefunc()'></ngo-button>

现在我想将两个类传递给按钮,但是当我尝试以这种方式传递它时,我收到错误

[类]='BTN 二'

我想,我们不允许在输入参数中添加空格,有没有另一种实现方法?

这是堆栈闪电战链接

<ngo-button [class]="'btn two'" (click)='somefunc()'></ngo-button>

Angular的默认语法。如果使用[input]表示法,则必须在引号中提供字符串。

否则:

<ngo-button class="btn two" (click)='somefunc()'></ngo-button>

虽然我不得不说,但它真的不明白为什么你使用输入来提供组件的类。

您可以使用 [ngClass]

<ngo-button [ngClass]="{'first class':{expression},'second class':{expression}}" (click)='somefunc()'></ngo-button>

注意:表达式像:真/假,2>1等。

记住:删除{表达式}的{}

如果你在 Angular 中使用方括号 [],你就是在告诉 Angular 编译器,接下来的内容是要解析的表达式。由于btn two不是有效的表达式,因此会出现解析错误。你真正想做的是:

[class]="'btn two'" .

值得一提的是,由于您选择将输入命名为"类",因此以后使用 Angular 时可能会遇到问题,既将值作为输入参数传入,又将值作为类应用于父元素。

最新更新