Angular 2 中自定义 HTML 标记上的自定义属性



我构建了一个组件

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-g-switch',
template: `
<div id="switch" (click)='toggle()' [ngStyle]="{'background-image': 'url('+photo+')'}"></div>
`,
styleUrls: ['./g-switch.component.scss']
})
export class GSwitchComponent implements OnInit {
_value: number;
photo = '../../assets/sw-1-1.png';
constructor() { }
ngOnInit() {
// this._value = 1;
}
public returnValue(): number {
return this._value;
}
toggle() {
this._value++;
if (this._value === 4) {
this._value = 1;
}
this.photo = '../../assets/sw-1-' + this._value + '.png';
}
}

我包含在我的模板中

<app-g-switch #sw1></app-g-switch>

我希望能够将值传递给组件,我以前见过这样的,

<app-g-switch #sw1 [value]="2"></app-g-switch>

如何实现这一点?我试图实现一个二传手,但它没有用。

Angular 文档在其模板和数据绑定文档下有一个子部分,描述了您正在寻找的@Input@Output模板语法。

请参阅 Angular 关于输入和输出属性的文档。

<小时 />

示例

在您的方案中,您希望能够从组件选择器上的 HTML 指令初始化_value变量。

使用 @Input 装饰器标记_value以将其声明为输入指令字段。

@Input
_value: number;

现在,您可以从组件选择器中设置_value参数,如下所示:

<app-g-switch [_value]="1"> </app-g-switch>

最新更新