Angular:从组件中的指令调用方法

标签 angular typescript angular-directive

我正在尝试从指令中调用方法。 可以说我有指令 我的指令.ts

@Directive({
  selector: '[something]',
})
export class myDirective implements OnInit {
....
public myMethod(){
console.log(it works)
}
....
}

和 component.ts(这是我发现的,但在 this.directive 上我得到错误对象可能为空)

@Component({
  selector: '...',
  templateUrl: '....html',
  styleUrls: ['....css'],
})
export class MyComponent implements OnInit {
  @ViewChild(myDirective) directive = null

  ngOnInit() {
  }

  onClickFunction() {
    return (
      this.directive.myMethod();
    );
  }
}

如何在组件中调用这个方法?

最佳答案

就这样跑

@Component({
  selector: '...',
  templateUrl: '....html',
  styleUrls: ['....css'],
})
export class MyComponent implements OnInit {
  @ViewChild(myDirective) directive;

  ngOnInit() {
  }

  onClickFunction() {
    return (
      this.directive?.myMethod()
    );
  }
}

在tsconfig.json中添加

"strictPropertyInitialization":false,

关于Angular:从组件中的指令调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68496881/

相关文章:

angular - Graphql 与数组类型的变异

Angular4 路由 : Force Navigation By Bypassing Route Guard

typescript - Rollupjs 不捆绑所有文件

javascript - 在 Angular 9 的 elemntRef 中找不到 Div 的内部文本

angular - 无法在单元测试用例中调用@HostListener方法

angular - 指令在子模块中不起作用

javascript - Angular Directive(指令)传入范围值未定义

Angular 阻塞(同步)http 调用

node.js - 如何将类验证器实现为中间件?

angular - Angular 动态形式的单选按钮