简体   繁体   English

Angular 2将HTML属性从父级传递到子级

[英]Angular 2 passing html attributes from parent to child

I want to pass attribute of HTML from parent to child. 我想将HTML的属性从父级传递到子级。 Is there any way where I can directly pass attribute from a parent without creating a variable for it in parent's .ts class and then passing it. 有什么方法可以直接从父级传递属性,而无需在父级的.ts类中为其创建变量,然后再传递它。 Here is sample code of parent 这是父母的示例代码

<app-field-lable type="number"></app-field-lable>

and here is my field label component. 这是我的字段标签组件。

<input [(ngModel)]="signageRequest.brandingSpaceName"  class="form-control"/>

As you can see I am passing type="number" attribute from a parent, but it ain't working. 如您所见,我正在从父级传递type =“ number”属性,但是它不起作用。 I know the mechanism to create a variable in parent and then passing it to child via a @Input decorator. 我知道在父级中创建变量,然后通过@Input装饰器将其传递给子级的机制。 But is there a way where I do not have to create all of the variables in a parent class and pass it directly to a child. 但是有没有一种方法,我不必在父类中创建所有变量并将其直接传递给子代。

Thanks 谢谢

You can just put string as @Input : 您可以将string作为@Input

<app-field-lable [inputType]="'number'"></app-field-lable>

Here is sample for Ts file and how you can use it in html 这是Ts文件的示例,以及如何在html中使用它

@Component({
 selector: 'app-field-lable',
 template: '<input type="{{inputType}}"/>',
 styleUrls: ['./field-lable.component.css']
})
export class FieldLableComponent implements OnInit {
 @Input() inputType:string;
 constructor() { }
 ngOnInit{}
}

Main idea, that native attributes (like type ) expects strings, but @Input() attributes (like [customAttr] ) expects variables 主要思想是,本机属性(如type )需要字符串,但@Input()属性(如[customAttr] )需要变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM