简体   繁体   中英

Can't bind to 'appIfRoles' since it isn't a known property of 'p'

I wanted to implement View Component Based On User Role In Angular 10 , to hide and show component. But I am block with the error above. Does anyone here has an idea about the issue? Help and idea would be much appreciated. Thanks.

#Role service code

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";

/**
 * The Role Service service
 */
@Injectable()
export class RolesService {
  private rolesAPi: string = "https://api.npoint.io/97c436983e2fbacffc7f";

  constructor(private http: HttpClient) {}

  /**
   * gets the user role
   */
  public roles(): Observable<{ roles: string[] }> {
    return this.http.get<{ roles: string[] }>(this.rolesAPi);
  }
}

component.html code

<p *appIfRoles='["Admin"]'>
    ADMIN CONTENT IS VIEWED
  </p>

if-roles.directive.ts directive code

import { Input, OnInit, Directive, ViewContainerRef, TemplateRef, OnDestroy } from "@angular/core";
import { Subject, Subscription } from "rxjs";
import { takeUntil } from "rxjs/operators";
import { RolesService } from "../../core/services/user-role.service"


@Directive({
  selector: '[appIfRoles]'
})
export class IfRolesDirective implements OnInit, OnDestroy {
  private subscription: Subscription[] = [];
  // the role the user must have
  @Input() public ifRoles: Array<string>;

  /**
   * @param {ViewContainerRef} viewContainerRef -- the location where we need to render the templateRef
   * @param {TemplateRef<any>} templateRef -- the templateRef to be potentially rendered
   * @param {RolesService} rolesService -- will give us access to the roles a user has
   */
  constructor(
    private viewContainerRef: ViewContainerRef,
    private templateRef: TemplateRef<any>,
    private rolesService: RolesService
  ) {}

  public ngOnInit(): void {
    this.subscription.push(
      this.rolesService.roles().subscribe(res => {
        if (!res.roles) {
          // Remove element from DOM
          this.viewContainerRef.clear();
        }
        // user Role are checked by a Roles mention in DOM
        const idx = res.roles.findIndex((element) => this.ifRoles.indexOf(element) !== -1);
        if (idx < 0) {
          this.viewContainerRef.clear();
        } else {
          // appends the ref element to DOM
          this.viewContainerRef.createEmbeddedView(this.templateRef);
        }
      })
    );
  }

  /**
   * on destroy cancels the API if its fetching.
   */
  public ngOnDestroy(): void {
    this.subscription.forEach((subscription: Subscription) => subscription.unsubscribe());
  }
}

app.module.ts code

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router';

import { LoginComponent } from './core/pages/login/login.component';
import { DashboardComponent } from './core/pages/dashboard/dashboard.component';


import { LayoutModule } from '@angular/cdk/layout';
import { SideNavComponent } from './core/components/side-nav/side-nav.component';
import { HeaderBarComponent } from './core/components/header-bar/header-bar.component';
import { UserprofileComponent } from './core/components/userprofile/userprofile.component';
import { UserInviteFormDialogComponent } from './core/components/user-invite-form-dialog/user-invite-form-dialog.component';
import { HeaderInterceptor } from './core/interceptors/header.interceptor';
import { RolesService } from './core/services/user-role.service';

import { SharedModule } from './shared/shared.module';
//import { AgmCoreModule } from '@agm/core';
import { ToastrModule } from 'ngx-toastr';
import { NgxMaskModule, IConfig } from 'ngx-mask';
import { IfRolesDirective } from './shared/directives/if-roles.directive';


// import { CoreModule } from './core/core.module';

const ngMaskConfig: Partial<IConfig> = {
  validation: false,
};

@NgModule({
  declarations: [
    AppComponent,
    IfRolesDirective,
    LoginComponent,
    DashboardComponent,    
    SideNavComponent,
    HeaderBarComponent,
    UserprofileComponent,    
    UserInviteFormDialogComponent, 
    ,
    
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    LayoutModule,
    RouterModule,        
    HttpClientModule,
    // CoreModule,
    ToastrModule.forRoot({
      preventDuplicates: true,
      enableHtml: true,
      progressBar: true
    }),
    SharedModule,
     NgxMaskModule.forRoot(ngMaskConfig),  
  ],
  providers: [{
      provide: HTTP_INTERCEPTORS,
      useClass: HeaderInterceptor,
      multi: true,},
      RolesService,],
  bootstrap: [AppComponent]
})
export class AppModule { }

You're almost there! Just missing the export in app.module.ts

@NgModule({
  declarations: [
    ...
    IfRolesDirective,
    ...],
  imports: [...],
  exports: [IfRolesDirective]
  providers: [...],
})
 

Try the following code.

<p *ifRoles='["Admin"]'>
    ADMIN CONTENT IS VIEWED
</p>


@Directive({
  selector: '[ifRoles]'
})
export class IfRolesDirective implements OnInit, OnDestroy {
  private subscription: Subscription[] = [];
  // the role the user must have
  @Input() public ifRoles: Array<string>;
  ....
  ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM