如何在Angular2中为@Input设置默认参数? [英] How to set default parameter for @Input in Angular2?

查看:68
本文介绍了如何在Angular2中为@Input设置默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个将显示name属性的组件,所以它大致是这样的:

Say I have a component that will display a name property, so it roughly goes like this:

import {Component, Input} from 'angular2/core';

@Component({
  selector: 'demo',
  template: `<div>{{name}}</div>`,
  styles: [``],
})
export class Demo {
  @Input() name: string;
}

问题是,当有人使用此组件但未传递任何name属性时,如何显示[noname]?

The problem is, how could I display [noname] when someone using this component but not passing any name property?

想到的唯一解决方案是在模板内使用像{{ name || '[noname]' }}这样的逻辑运算符.

The only solution comes to mind is using logic operator inside template like {{ name || '[noname]' }}.

推荐答案

尝试

@Input() name: string = 'noname';

这篇关于如何在Angular2中为@Input设置默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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