【问题标题】:Not able to give space as a value in the Input property in Angular6无法在 Angular6 的 Input 属性中提供空间作为值
【发布时间】:2019-06-19 08:58:47
【问题描述】:

我正在尝试创建这样的通用控件

动态控制.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';
}

main-component.html

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

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

[class]='btn 两个'

我想,我们不允许在输入参数中添加空格,还有其他方法来实现吗?

this is the stackblitz link

【问题讨论】:

    标签: angular angular6 angular-input


    【解决方案1】:
    <ngo-button [class]="'btn two'" (click)='somefunc()'></ngo-button>
    

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

    否则:

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

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

    【讨论】:

      【解决方案2】:

      你可以使用 [ngClass]

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

      注意: 表达式类似于:真/假、2>1 等

      记住:移除 {expression} 的 {}

      【讨论】:

      • 这不会导致与问题相同的行为,因为这些类应用于宿主元素 &lt;ngo-button&gt; 而不是内部模板 &lt;button&gt;
      【解决方案3】:

      如果你在 Angular 中使用方括号 [],你是在告诉 Angular 编译器后面的内容是一个要解析的表达式。由于btn two 不是有效的表达式,因此您会遇到解析错误。你真正想做的是:

      [class]="'btn two'".

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

      【讨论】:

      • 您提供了另一个错误的语法(另外,请考虑对现有答案进行投票而不是模仿它)
      • @Maryannah 当我发表评论时,您的答案不存在。只有在我刷新时才会出现。
      • 当然,我明白了,那么您不会介意删除它:) 无论如何,如果您愿意,请保留它,我只是为您提供在堆栈溢出时采用的最佳实践
      猜你喜欢
      • 2021-04-07
      • 2023-03-14
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 2019-01-02
      相关资源
      最近更新 更多