Primeng P-меню отключить пункт меню программно на основе логической проверки - PullRequest
0 голосов
/ 24 января 2020

У меня есть приложение Angular 8, где я использую p-menu и пункты меню для отображения меню. Я нахожусь в ситуации, когда мне нужно проверить логи c зависит от другого API. Если logi c возвращает true, тогда моя локальная логическая переменная установлена ​​в true.

Теперь проблема в том, что для переменной задано значение true. Я вижу, что в журнале консоли, когда я передаю эту переменную в menu items array, ничего не происходит. Не уверен, почему значение переменной здесь не берется.

В моем component.ts:

    export class AddInCommandsComponent implements OnInit, AfterViewInit {
        dataModel: AuthListModel = {
            apiKey: this.configService.apiKey,
            appURL: this.configService.appUrl,
        };
        items: MenuItem[];
        noTaskFound = false;


        ngOnInit() {

         this.items = [
            {
                label: 'Resources',
                items: [

                    {
                        label: 'Import & Map Resources',
                        icon: 'ms-Icon ms-Icon--Handwriting ms-fontSize-32 ',
                        title:
                            ' Retrieves Time Writers from Tidy & Map existing resources to Tidy Time Writers',
                        command: event => this.showMapResourcesScreen(),
                        disabled: this.noTaskFound,
                    },
                ],
            },
       ];
          }

Примечание: В приведенном выше примере вы можете видеть, что свойство disabled установлено по локальной переменной.

И ниже мой метод, который был выполнен в конструкторе. Журнал показывает this.noTaskfound = true

async checkResourceExist() {
        const ResourceMaxIndex = await this.projectTaskService.getMaxResourceIndex();
        console.log('check resource exec');
        console.log('Resource MaxIndex', ResourceMaxIndex);
        if (ResourceMaxIndex === 0) {
            this.noTaskFound = true;
            console.log('no task found:', this.noTaskFound);
        }
    }

Может кто-нибудь, пожалуйста, помогите, как добиться этого программным путем.

1 Ответ

0 голосов
/ 26 января 2020

Может быть, это поможет тому, кто хочет disable menu item программно.

Примечание. Используйте одно из событий жизненного цикла Angular с именем ngAfterContentChecked

Шаг 1. В файле component.ts в части экспорта добавьте ngAfterContentChecked

export class AddInCommandsComponent
    implements OnInit, AfterViewInit, AfterContentChecked {

И затем добавьте соответствующий импорт

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

Шаг 2: В том же файле component.ts

   ngAfterContentChecked(): void {
        this.ref.detectChanges();
        this.items = [
            {
                label: 'Resources',
                items: [
                    {
                        label: 'Import & Map Resources',
                        icon: 'ms-Icon ms-Icon--Handwriting ms-fontSize-32 ',
                        title:
                            ' Retrieves Time Writers',
                        command: event => this.showMapResourcesScreen(),
                        disabled: this.noTaskFound,
                    },
                ],
            },
            {
                label: 'MS Project to Bamboo',
                items: [
                    {
                        label: 'Create Project in Bamboo',
                        icon: 'ms-Icon ms-Icon--Export ms-fontSize-32 ',
                        title:
                            'Export all tasks from this project into a new project in Tidy',
                        command: event => this.showCreateInScreen(),
                        disabled: this.noTaskFound,
                ],
            },
            /*            {
label: 'Bamboo to MS Project',
items: [
{
label: 'Import Tasks from Bamboo',
icon: 'ms-Icon ms-Icon--Import ms-fontSize-32 ',
title:
'Import all tasks from Bamboo into a blank project',
command: event => this.showImportFromScreen(),
},
{
label: 'Update Tasks from Bamboo',
icon: 'ms-Icon ms-Icon--PostUpdate ms-fontSize-32',
title:
'Update all tasks in this project from changes made in Bamboo',
disabled: true,
},
],
},*/
        ];
    }

Помните: ngAfterViewInit выдаст Expression changed error.

Надеюсь, это поможет.

...