How to perform the Onclick event in primeNG menu bar

1338 views angular
-3

How to perform the On-click event using the PrimeNG.

When we click on the New menu bar to get the UserFormComponent.html page to Add new user.Using PrimeNG how can we perform this.

appcomponent.html

<p-menubar [model]="items">

appcomponent.ts

export class AppComponent {
  title = 'clientApp';
  private items: MenuItem[];

  ngOnInit() {
    this.items = [
    {
      label: 'Quotes',
      items: [
        { label: 'New ', icon: 'fa fa-refresh', routerLink:"/demo" },
        { label: 'Show All', icon: 'fa fa-repeat', url: '#' }             
      ]
    }

this is my UserFormComponent.html

<div class="container">
  <form (ngSubmit)="processForm()">      
      <div class="form group">
        <label for="username">User Name</label>
        <input type="text" name="username" class="form-control" [(ngModel)]="user.username">
      </div>
      <div class="form group">
          <label for="type">Type</label>
          <input type="text" name="type" class="form-control" [(ngModel)]="user.type">
      </div>

      <div class="form group">
        <label for="modelname">Model Name</label>
        <input type="text" name="modelname" class="form-control" [(ngModel)]="user.modelname">
      </div> 
            <input type="submit" value="save" class="btn btn-success">
  </form>
</div>

this is my UserFormComponent.ts

export class UserFormComponent implements OnInit {
  private user:User;
  constructor(private _userService:UserService,private _router:Router) {

   }

  ngOnInit() {
  this.user=this._userService.getter();
  }

  processForm(){
    if(this.user.id==undefined){
       this._userService.createUser(this.user).subscribe((user)=>{
         console.log(user);
         this._router.navigate(['/']);
       },(error)=>{
         console.log(error);
       });
    }else{
       this._userService.updateUser(this.user).subscribe((user)=>{
         console.log(user);
         this._router.navigate(['/']);
       },(error)=>{
         console.log(error);
       });
    }
  }

answered question

1 Answer

8

You can use command to call function.

ts

ngOnInit() {
    this.items = [
    {
      label: 'Quotes',
      items: [
        { label: 'New ', 
           icon: 'fa fa-refresh', 
           command: () => addNewUser(),
           //routerLink:"/demo"  <-- this can be moved inside the addNewUser function.
        },
        { label: 'Show All', icon: 'fa fa-repeat', url: '#' }             
      ]
    }

//Add new user
addNewUser(){
   this.user=this._userService.getter();
}

posted this

Have an answer?

JD

Please login first before posting an answer.