【问题标题】:Angular 8, trouble calling function from another componentAngular 8,从另一个组件调用函数时遇到问题
【发布时间】:2020-05-19 07:04:31
【问题描述】:

尝试从不同的组件调用创建标签模式。

我正在使用的组件称为宠物,位于: app/main/ClientPatientManagement/Pets

尝试访问 show() 方法: app/main/tags/tags/create-or-edit-tag-modal.component'

这是我 Pets.Component 中的代码:

    import { CreateOrEditTagModalComponent } from '@app/main/tags/tags/create-or-edit-tag-modal.component';
@Component({
    templateUrl: './pets.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class PetsComponent extends AppComponentBase {

    @ViewChild('createOrEditTagModal', { static: true }) createOrEditTagModal: CreateOrEditTagModalComponent;

这里有一些其他代码,包括 ngOnInit 等,但我想在按下按钮时调用以下函数:

createTag(): void {
        this.createOrEditTagModal.show();
    }

我的问题是我不断收到错误消息说我的 this.createOrEditTagModal 未定义。

我还在我的 main.module.ts 中导入了这个组件并将其添加到我的声明中。

谁能帮我解释为什么这一直是未定义的?

编辑: 为了完整起见,我添加了一些来自 create-or-edit-tag-modal-component 的代码

@Component({
    selector: 'createOrEditTagModal',
    templateUrl: './create-or-edit-tag-modal.component.html'
})
export class CreateOrEditTagModalComponent extends AppComponentBase {

    @ViewChild('createOrEditModal', { static: true }) modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    constructor(
        injector: Injector,
        private _tagsServiceProxy: TagsServiceProxy
    ) {
        super(injector);
    }


    show():void{
        console.info("Called tag component successfully!"); //for testing
    }

【问题讨论】:

  • create-or-edit-tag-modal 中是否有类?您是否尝试过添加@Injectable?
  • 嗨 Tsakiroglou,create-or-edit-tag-modal 中有一个类,我更新了我的问题以包含其中的摘录。你能发现那里有什么问题吗?
  • 哦,我明白了,谢谢,恐怕我什么也没看到。我会深入研究。

标签: angular angular8


【解决方案1】:

好消息,找到问题了!

问题出在我的 pets.component.html 中。 我忘了在那里声明我的模态,所以我在 pets.component.html 中添加了这个:

<createOrEditTagModal #createOrEditTagModal (modalSave)="getPets()"></createOrEditTagModal>

这可以解决问题,现在运行平稳且无错误。 请注意,getPets() 函数是在 modal 自己的保存函数之后调用的,所以它基本上只是刷新页面。

【讨论】:

    【解决方案2】:

    我认为您的代码中的第一个参数是错误的。

    @ViewChild('createOrEditTagModal', { static: true }) createOrEditTagModal: CreateOrEditTagModalComponent;

    应该改成

    @ViewChild(CreateOrEditTagModalComponent, { static: true }) createOrEditTagModal: CreateOrEditTagModalComponent;

    另外,请确保 pets.component.html 中包含 CreateOrEditTagModalComponent。

    【讨论】:

    • 迪宁杜晚安。感谢您的输入。我已经尝试过了,但它似乎没有任何影响。吐出完全相同的错误。
    • 嗨格瑞特。我看到你已经解决了这个问题,我的回答中也提到了。->>>>“另外,请确保 pets.component.html 中有 CreateOrEditTagModalComponent 。”
    • 感谢 Dinindu,我将您的答案标记为有用,它可能会解决其他人的问题
    【解决方案3】:

    你能不能试着给一个这样的指令装饰器:

    @Directive({selector: 'createOrEditTagModal'})
    export class CreateOrEditTagModalComponent extends AppComponentBase {
    

    【讨论】:

      猜你喜欢
      • 2014-02-02
      • 2022-10-01
      • 2019-03-11
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 2020-03-18
      • 2019-07-24
      相关资源
      最近更新 更多