NguyenHung
NguyenHung

Reputation: 77

How to redirect with the least lines of code Angular 6

Commonly, this is the code used to redirect page

@Component({
  selector: 'app-inventory-status',
  templateUrl: './inventory-status.component.html',
  styleUrls: ['./inventory-status.component.css']
})
export class InventoryStatusComponent implements OnInit {

  constructor(private router: Router) { }

  ngOnInit() {
  }

  redirect(url) {
    this.router.navigateByUrl(url);
  }
}

In Html

<button type="button" class="btn btn-secondary bmd-btn-icon btn-back" (click)="redirect('/main/manager')">
   <i class="material-icons">arrow_back</i>
</button>

If I use code like above every file I have to import Router and create function redirect. How to put redirect function to common and only with one line I can redirect page. I do not use a tag. Thanks.

Upvotes: 0

Views: 51

Answers (1)

tausif
tausif

Reputation: 151

You can use angular routerLink directive in your template code. In this way you can avoid writing function.

@Component({
  selector: 'app-inventory-status',
  templateUrl: './inventory-status.component.html',
  styleUrls: ['./inventory-status.component.css']
})
export class InventoryStatusComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

Your template code will be

<a routerLink="/main/manager">
<button type="button" class="btn btn-secondary bmd-btn-icon btn-back">
   <i class="material-icons">arrow_back</i>
</button>
</a>

Upvotes: 3

Related Questions