指令的动态属性值 [英] Dynamic attribute values for directives

查看:22
本文介绍了指令的动态属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有以下注释的指令:

I have a directive with following annotation:

@Directive({
    selector: 'i-text-field[number-format]',
    providers: [NgModel]
})

在指令中,我使用输入注释获取属性值

In the directive I get the attribute value with the input annotation

export class NumberFormatDirective {

@Input('number-format') format: string;
...

现在例如我可以在组件中定义我的数字格式,如

Now e.g. I can define my number format in the component like

<i-text-field
label='Number' hint='00000,00'
number-format='7,2'
ngControl>
</i-text-field>

如何通过函数告诉组件使用哪种格式?

How can I a tell the component which format to use by using a function?

number-format='<<function-call>>'

推荐答案

看一看 这篇关于 Angular 2 模板语法的文章.假设您在组件中编写了一个名为 setNumberFormat() 的函数,您可以按如下方式设置 number-format 属性的值:

Take a look at this article on template syntax for Angular 2. Assuming you wrote a function called setNumberFormat() in your component, you could set the value of the number-format attribute as follows:

// my-component.ts
import { Component } from "@angular/core";
import { NumberFormatDirective } from "./number-format-directive.ts";

@Component({
    directives: [NumberFormatDirective],
    template: `
        <i-text-field
            label='Number' hint='00000,00'
            number-format='{{setNumberFormat()}}'
            ngControl>
        </i-text-field>
    `
})
export class MyComponent {

    setNumberFormat(): string {
        // code to set your number format, e.g.
        return "7,2";
    }
}

这篇关于指令的动态属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆