将数据传递到Angular Web组件

时间:2019-02-25 06:55:29

标签: angular web-component

我正在尝试用Angular编写Web组件,但似乎无法弄清楚如何将数据传递到组件中。

<my-component someId="1234"></my-component>

我希望找到某种方式来实现这一点,并在我的角度组件中获取someId。是否可以实现此功能,还是应该尝试使用插槽? 为了清楚起见,我要问的是如何使用角形而不是普通角形组件制作Web组件。

3 个答案:

答案 0 :(得分:0)

您应该使用Angular的data binding

<my-component [id]="1234"></my-component>

在子组件上,利用@Input decorators

export class MyComponent {
  @Input('id') id: string;
}

答案 1 :(得分:0)

您需要使用在共享组件中声明的@Input()变量。

export class MyComponent {
 @Input() someId: string = '1234';//default value
}

// HTML

<my-component someId="1234"></my-component>

“ someId”是可选的输入参数,也可以忽略。

编辑:在将某些常量字符串或数字绑定到输入的情况下,不必在方括号中指定。您可以使用与普通html属性相同的语法。

答案 2 :(得分:0)

我遇到了这个问题大约两天,最后我找到了解决方案。

您需要做的是在您的子组件(您要公开的网络组件)中使用 ngOnChanges() 方法。因为这是为了检测 @Input() 字段的任何变化。

这里我留下了我的网络组件的代码片段:

@Component({
  selector: 'app-shipment-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnChanges {

  @Input() domain;

  @Output() response = new EventEmitter<string>();

  constructor() {
  }

  ngOnInit(): void {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.domain) {
      console.log("Domain URL: ", this.domain);  
      this.response.emit(this.domain);
    }
  }

}
相关问题