繁体   English   中英

调用 Angular web 组件方法(CustomElement)

[英]Call Angular web component method (CustomElement)

我有这两个例子:

示例 1:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent {
  options:any = {isOpen: false };

  logOptions() {
    console.log(this.options);
  }

}

示例 2:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent {
  options:any = {isOpen: false };

  @Input() logOptions() {
    console.log(this.options);
  }

}

在 html 中:

<app-root></app-root>

<script>
  document.querySelector('app-root').logOptions();
</script>

在示例 1 中返回错误: document.querySelector(...).logOptions is not a function

在示例 2 中返回: undefined

有没有人有任何想法?

有点晚了,但如果你仍然需要这个,有几种方法可以让它工作。

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})

export class AppComponent {

    // @Input() << see comments below
    options: any = {isOpen: false };
    
    // This will NOT be available outside the component, in plain JS
    logOptions() {
        console.log(this.options);
    }

    // This will work ONLY if options is @Input()
    @Input()
    logOptions2() {
        console.log(this.options);
    }
    
    // This property will always provide correct data
    // Ideally a getter should not be @Input() though
    @Input()
    get logOptions3() {
        return this.options;
    }
}

您可以使用普通的JavaScript代码访问它们

const logComponentOptions = () => {
    const el = document.querySelector('app-root');
    // el.logOptions(); << Error
    el.logOptions2(); // works ONLY if options is @Input()
    console.log(el.logOptions3); // WORKS
    console.log(el.options); // if options is @Input()
}
  1. 所以logOptions3属性总是可以用来从普通的javaScript代码中获取options 但语义上不正确(作为@Input()getter
  2. 第一个logOptions()方法不能从外部访问,因为它没有标记为@Input()
  3. logOptions2()方法是可访问的,但只能打印正确的值,如果options也被标记为@Input()
  4. 但是,如果将options属性标记为@Input() ,则可以直接访问它本身,而不是将其包装在另一个方法中
  5. 最后,如果您只是简单地使@Input() options = false ,您也可以将其作为HTML的简单属性访问
<app-root options="false"></app-root>

更新

如果您想将数据传递到组件中,您可以简单地使用@Input公开一个setter属性。 然后您可以使用JavaScript从组件外部设置值

@Input()
public set myData(value: MyDataType) {
    // validation & logic if any
    this._myData = value;
}

// Then in JavaScript
const el = document.querySelector('app-root');
el.myData = {a: 10, b: true, c: 'my data object' }

暂无
暂无

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

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