【问题标题】:Angular 2 @Input - How to bind ID property of child component from parent component?Angular 2 @Input - 如何从父组件绑定子组件的 ID 属性?
【发布时间】:2017-02-15 12:15:31
【问题描述】:

在我的父组件中,我想创建一个具有与其关联的唯一 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”的值。它总是未定义的。

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

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

【问题讨论】:

  • this.ckEditorInstanceId 不起作用,你必须使用箭头函数
  • 我该怎么做?
  • iso function() {} 你写的 () => {}
  • 箭头函数有块作用域
  • 如果您可以发布代码示例,我们将不胜感激。我的大脑不知道该做什么:-/

标签: javascript angular input typescript output


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    诀窍是使用@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')
          });
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-13
      • 1970-01-01
      • 2017-05-18
      • 2016-05-21
      • 2017-11-29
      • 2021-02-23
      • 2019-05-05
      • 2016-07-21
      • 2020-03-08
      相关资源
      最近更新 更多