簡體   English   中英

從另一個組件調用一個 Angular 組件時出現問題

[英]Problem calling one Angular component from another component

在工作中,我在使用 Angular 時遇到了問題。 我有這種 Angular 組件:

@Component({
selector: 'foo',
templateUrl: 'foo.html'
})
export class FooComponent {
  @Input() data: string;
  content: string;
  ngOnInit() {
    this.content = this.data;
  }
  setValue(data) {
    this.content = data;
  }
}

這是從我的主要 Angular 組件在代碼塊中初始化的,例如:

this.components = [FooComponent, BarComponent, BazComponent, QuuxComponent];

現在這有效。 但是,如果我嘗試使用this.components[0].setValue("Hello world!");調用setValue()函數this.components[0].setValue("Hello world!"); 我收到錯誤消息“ this.components[0].setValue is not a function.

這是什么原因,我該如何解決?

這似乎是處理 angular 組件的一種非常非常奇怪的方式。

  • 您真的不想通過從另一個組件調用一個組件內的方法來破壞封裝。
  • 我個人還沒有在任何地方看到過這種組件引用(並且懷疑這是一種正確的方法)。
  • 沒有理由在內容中復制數據屬性。

您可以在模板中傳遞值。 或者,如果您無法直接訪問模板,請使用服務。

這是一個非常基本的示例,說明如何使用模板和@Input修改來自父級的數據。

app.component.ts

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  message = "I am a message from the parent";
}

應用程序組件.html

<app-child [content]='message'></app-child>

子組件.ts

import { Component, OnInit, Input } from "@angular/core";

@Component({
  selector: "app-child",
  templateUrl: "./child.component.html",
  styleUrls: ["./child.component.css"]
})
export class ChildComponent implements OnInit {
  @Input("content") public content: string;

  constructor() {}

  ngOnInit() {}
}

子組件.html

<p>{{content}}</p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM