【问题标题】:Changing attributes value in angular2 template更改 angular2 模板中的属性值
【发布时间】:2016-09-13 21:07:03
【问题描述】:

我有简单的 angular2 组件:

import {Component} from 'angular2/core';
@Component({
  selector: 'circle',
  template: `<svg height="100" width="100">
    <circle cx="50" cy="50" r="40" stroke="black" 
      stroke-width="3" fill="red" />
    </svg>`,
})  
export class Circle { }

我想使用组件的某些参数动态更改fill 属性,例如&lt;circle color="red"&gt;&lt;/circle&gt;,结果有红色圆圈。有可能吗?

【问题讨论】:

    标签: svg angular angular2-directives


    【解决方案1】:

    您可以将[...] 语法与attr 前缀一起用于您的属性。请参阅以下内容:

    @Component({
      selector: 'circle',
      template: `<svg height="100" width="100">
        <circle cx="50" cy="50" r="40" stroke="black" 
          stroke-width="3" [attr.fill]="fillAttr" />
        </svg>`,
    })  
    export class Circle {
      fillAttr:string = 'red';
    }
    

    如果您想为组件提供输入,请使用 @Input 装饰器:

    @Component({
      selector: 'circle',
      (...)
    })
    export class Circle {
      @Input('color')
      fillAttr:string = 'red';
    }
    

    【讨论】:

    • 谢谢,但我怎样才能将数据从圆形元素属性传递给fillAttr
    • 你的意思是在使用你的组件时?
    • 是的,比如&lt;circle color="red"&gt;&lt;/circle&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    相关资源
    最近更新 更多