【问题标题】:In Angular 2 how to put array string elements into template element value-attribute?在 Angular 2 中,如何将数组字符串元素放入模板元素值属性中?
【发布时间】:2017-07-04 20:01:01
【问题描述】:

我的 Angular 2 组件类中有一个名为 myArray 的数组:

@Component({
    templateUrl: 'my.component.html'
})

export class MyComponent {
    private myArray: Array<string>;
    ...
}

在 my.component.html 我有一个输入元素:

<input placeholder='write some tags' value=''>

我想要的是将 myArray 的字符串元素插入到输入元素的 value 属性中。字符串应该用逗号分隔。比如:

<input placeholder='write some tags' value='apple, orange, banana'>

我试过了:

<input name='user-tag' placeholder='write some tags' value='*ngFor="let e of myArray"{{e}}'>

但这产生了错误。

我该怎么做?

【问题讨论】:

    标签: javascript jquery angular typescript


    【解决方案1】:

    不用*ngFor,试试Array.join()

    <input name='user-tag' placeholder='write some tags' value='{{ myArray.join(', ') }}'>
    

    【讨论】:

    • 我建议你创建一个过滤器来做这种事情,这样你就会有一个单一的参考点,当需要一些改进时,你不需要改变多个地方。
    • 当然,pipe 非常适合您所描述的内容,但我不想过度设计答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 2018-01-09
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多