使用@viewChild从我的组件触发其他组件功能

时间:2017-11-14 06:13:54

标签: angular

在我的应用程序中,我有多个组件,因为我必须从一个组件触发其他组件功能。两个组件之间没有任何关系。在这种情况下尝试使用@viewChild。

在调用函数时遇到TypeError:无法读取属性' showHelp'未定义的错误。

@viewChild仅用于父子组件交互,这是否只能通过服务实现?

class Story(models.Model):
    writer = models.CharField(max_length=189)
    title = models.CharField(max_length=189)


class Block(models.Model):
    story = models.ForeignKey(Story, related_name='+', on_delete=models.CASCADE)
    block = EnumField(choices=[
        ('TXT', "text"),
        ('IMG', "image"),
    ])
    serial = models.IntegerField(default=0)

    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)


class TextBlock(Block):
    type = models.CharField(max_length=128, blank=True, null=True, default='paragraph')
    content = models.TextField(blank=True, null=True)


class ImageBlock(Block):
    src = models.URLField()
    type = models.CharField(max_length=128, blank=True, null=True, default='full')
    title = models.CharField(max_length=189, blank=True, null=True)
    photographer = models.CharField(max_length=128, blank=True, null=True)

1 个答案:

答案 0 :(得分:0)

下面是Child组件,您可以在其中发送按钮单击时的一些值,将选择下拉到父组件。单击按钮,我们将从名为值

的子组件触发childToParent事件
import { Component, Input, Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <input type="textbox" [(ngModel)]='masterName'>
    <button (click)="sendToParent(masterName)" >sendToParent</button>
  `
})
export class AppChildComponent {
  //getting value from parent to child
  @Input('master') masterName: string;

  @Output() childToParent = new EventEmitter<String>();

  sendToParent(name){
    this.childToParent.emit(name);
  }
}

下面是主组件,其中{child}方法是从具有发射值的子组件触发的。

childToParent

You can refer this link for working version