【问题标题】:how to call a typescript method on button click which is present in different .ts file?如何在不同的.ts文件中单击按钮时调用打字稿方法?
【发布时间】:2020-07-30 14:50:25
【问题描述】:

我有两个 .ts 文件(editor.ts 和 editor_settings.ts),对应于 editor.ts 我有创建者 editor.html 文件。现在我试图在 editor.html 中单击按钮时调用 editor_settings.ts 中的函数。

editor.ts

import { EditorSetting } from '../app/editorSetting.component';
export class PadComponent implements OnInit, OnDestroy { ---- }
constructor(
    private component: EditorSetting

) { }
    submit() {
    let userCode = this.component.editor.getValue();
    console.log('Inside pad.componet.ts');
    console.log(userCode);
}

editor.html

<button id="submit" type="button" class="btn btn-sm btn-run" (click)="submit()" [disabled]="loading" 
        style="background: #FF473A">
         <i class="fa fa-play" aria-hidden="true"></i>
          <span *ngIf="loading">Running</span>
          <span else> Run </span>
    </button>

现在,在 editor.html 中单击按钮时,我想调用 editor_settings.ts 中的函数。

editor_settings.ts

export class EditorComponent implements OnInit, OnDestroy, OnChanges {--}

我面临以下错误:

inline template:0:0 caused by: No provider for EditorComponent!

【问题讨论】:

  • 您的意思是 2 个不同的组件,对吧?你想在兄弟组件中调用方法吗?
  • 您是否将EditorSetting模块的链接添加到Editor组件的模块中????

标签: html angular typescript angular8


【解决方案1】:

要对彼此不相关的两个组件进行通信,您可以使用服务。

@Injectable({
    providedIn: 'root',
})
export class YourService {

    private yourVariable: Subject<any> = new Subject<any>();


    public listenYourVariable() {
        return this.yourVariable.asObservable();

    }


    public yourVariableObserver(value ?: type) {
        this.yourVariable.next(value);
    }

你在你想要使用这个服务的地方导入你的组件。

import{ YourService } from ...

在编辑组件中:

submit(){
    this.yourService.yourVariableObserver();
}

在 Editor_setting.ts 中

 ngOnInit() {
   this.sub=this.yourService.listenYourVariable().subscribe(
            variable => {
              this.callyourFunction();
            }

        )
    }

不要忘记取消订阅以防止内存泄漏

 ngOnDestroy() {
  this.sub.unsubscribe()
}

【讨论】:

    【解决方案2】:

    如果您的编辑器位于 editorSetting 中,则另一种方法有效

    <editor-setting>
       <editor></editor>
    </editor-setting>
    

    在构造函数中使用 Host

    constructor(@Optional @Host() private component: EditorSetting) { }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      相关资源
      最近更新 更多