我创建了一个我想要调用的子组件.

当我调用这个方法时,它只触发console.log()行,不会设置test属性??

下面是快速启动Angular应用程序和我的更改.

Parent

import { Component } from '@angular/core';
import { NotifyComponent }  from './notify.component';

@Component({
    selector: 'my-app',
    template:
    `
    <button (click)="submit()">Call Child Component Method</button>
    `
})
export class AppComponent {
    private notify: NotifyComponent;

    constructor() { 
      this.notify = new NotifyComponent();
    }

    submit(): void {
        // execute child component method
        notify.callMethod();
    }
}

Child

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

@Component({
    selector: 'notify',
    template: '<h3>Notify {{test}}</h3>'
})
export class NotifyComponent implements OnInit {
   test:string; 
   constructor() { }

    ngOnInit() { }

    callMethod(): void {
        console.log('successfully executed.');
        this.test = 'Me';
    }
}

如何设置test属性?

推荐答案

你可以使用@ViewChild来获取更多信息,请查看link

With type selector

子组件

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}

父组件

@Component({
  selector: 'some-cmp',
  template: '<child-cmp></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {

  @ViewChild(ChildCmp) child:ChildCmp;

  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

With string selector

子组件

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}

父组件

@Component({
  selector: 'some-cmp',
  template: '<child-cmp #child></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {

  @ViewChild('child') child:ChildCmp;

  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

Typescript相关问答推荐

如何根据服务响应构建子路由

从传递的数组中出现的值设置返回键的类型

如何在类型脚本中使用条件陈述循环

强制两个类型脚本对象具有相同的键

类型脚本:类型是通用的,只能索引以供阅读.(2862)"

如何将绑定到实例的类方法复制到类型脚本中的普通对象?

VS代码1.88.0中未出现自动导入建议

属性的类型,该属性是类的键,其值是所需类型

在Typescribe中,extends工作,但当指定派生给super时出错""

我用相同的Redux—Toolkit查询同时呈现两个不同的组件,但使用不同的参数

如何将联合文字类型限制为文字类型之一

打字类型保护递归判断

TypeScrip省略了类型参数,仅当传递另一个前面的类型参数时才采用默认类型

重载函数的T helper参数

Typescript 中相同类型的不同结果

如何避免从引用<;字符串&>到引用<;字符串|未定义&>;的不安全赋值?

从类型脚本中元组的尾部获取第n个类型

接口中可选嵌套属性的类型判断

在类型脚本中创建显式不安全的私有类成员访问函数

我是否应该在 Next.js 中的服务器组件中获取秘密数据的所有函数中使用使用服务器?