@Input——如何从父组件绑定子组件的ID属性

Angular 2 @Input - How to bind ID property of child component from parent component?

本文关键字:组件 ID 属性 绑定 @Input      更新时间:2023-09-26

在父组件中,我想创建一个具有唯一ID的子组件,并且我想将该唯一ID传递给子组件,以便子组件可以将该ID放在其模板上。

父模板:

<ckeditor [ckEditorInstanceID]="someUniqueID"> </ckeditor>

下面是子组件:

import { Component, Input } from '@angular/core'
var loadScript = require('scriptjs');
declare var CKEDITOR;
@Component({
   selector: 'ckeditor',
   template: `<div [id]="ckEditorInstanceID">This will be my editor</div>`
})
export class CKEditor {
   @Input() ckEditorInstanceID: string;
   constructor() {
      console.log(this.ckEditorInstanceID)
   }
   ngOnInit() {
   }
   ngAfterViewInit() {
      loadScript('//cdn.ckeditor.com/4.5.11/standard/ckeditor.js', function() {
         CKEDITOR.replace(this.ckEditorInstanceID);
         console.info('CKEditor loaded async')
      });
   }
}

我错过了什么?我似乎无法让子组件接收"someUniqueID"的值。

UPDATE:我能够让子组件接收值"someUniqueID "。上面更新的代码。但是,我不能通过调用this.ckEditorInstanceID引用@Input属性,因为this是未定义的。

如何引用我通过@Input引入的属性?

不要将输入命名为id。这与HTMLElementid属性相冲突。

技巧是使用像@David Bulte提到的箭头函数。

loadScript('//cdn.ckeditor.com/4.5.11/standard/ckeditor.js', () => {
     CKEDITOR.replace(this.ckEditorInstanceID);
     console.info('CKEditor loaded async')
  });

由于某种原因,箭头函数可以访问this.ckEditorInstanceID,但是常规函数(){}不能访问this.ckEditorInstanceID。我不知道为什么,也许有人能告诉我原因。

另外,我必须像这样修改我的标记:

<ckeditor [ckEditorInstanceID]="'editor1'"> </ckeditor>
<ckeditor [ckEditorInstanceID]="'editor2'"> </ckeditor>

并将@Input属性设置为[]中的名称,即ckEditorInstanceID,并且模板源应该是属性名称ckEditorInstanceID,如[id]="ckEditorInstanceID"

从父html选择器接收ID的完整工作子组件:

import { Component, Input } from '@angular/core'
var loadScript = require('scriptjs');
declare var CKEDITOR;
@Component({
   selector: 'ckeditor',
   template: `<div [id]="ckEditorInstanceID">This will be my editor</div>`
})
export class CKEditor {
   @Input() ckEditorInstanceID: string;
   constructor() {}
   ngAfterViewInit() {
      loadScript('//cdn.ckeditor.com/4.5.11/standard/ckeditor.js', () => {
         CKEDITOR.replace(this.ckEditorInstanceID);
         console.info('CKEditor loaded async')
      });
   }
}