A simple guide to Build Angular Reactive Templates with Ngif and Async Pipe


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

Angular Templates seamlessly help to expedite the development process with flawless assistance of components and other specific elements. These are dynamic and renders according to the directive instructions. To put it simply, Angular templates help in developing modern applications with a modest look. In this blog, we will discuss how to build Angular Templates with NgIf and Async pipe.

There are several benefits of writing Angular templates. Some crucial ones are:

  1. Reduced memory usage (depending on the type of Observable we use)
  2. More readable code.
  3. Fewer potential points with multiple subscriptions at the level of the service layer.
  4. Less state in our components.

Overall, this is an excellent way to write readable templates while avoiding by design based problems.

Ngif Else Example in Angular

Let's take a look at the Ngif Else syntax given below as an example:

Condition is true ...

Condition is false ...

We can specify in Ngif an else part with the name of a template, that will change the element where Ngif is put near in case the condition is false.

This will either display Condition is true or the satisfaction of the loading template to the element annotated with Ngif, depends on the truthfulness of the condition.

The Ngif as Syntax in Angular

With Ngif, it is also possible to analyze the truthfulness of an expression and assigning the result of the expression to a variable.

Let's see an example:

@Component ({
  selector: 'app-root',
  template: `
    

{{result.description}}

Condition is false ...

`}) export class AppComponent implements OnInit { course = { id:1, description: 'Angular For Beginners' }; }
  1. The template above would display Angular for startup because the expression course is truthful. As we can see, the course corresponding to a component property which is a simple JavaScript (Type Script) object.
  2. The result of the expression is not a boolean but anything like char, etc. It is an instance and gets assigned to a local template variable named result, and so the description property gets in display to the screen as expected which makes it much simple to write our templates in a different Reactive Style.


Why use the Async pipe?

Because it automatically subscribes and unsubscribes from Observable as the component gets instant or destroyed, which is a big feature.

This is mainly required in the case of long-lived observably like for example exactly Observable returned by the router or via Angular Fire.

In addition, because it makes our programs easier to read and more declarative, with fewer state variables in our component classes.

So, let's use the Async pipe here:

{{(courseObs | async)?.shortDescription}}
{{(courseObs | async)?.longDescription}}
{{( courseObs | async)?.duration}}
{{( courseObs | async)?.flags}}

However, this not very convenient because we need to use the Async pipe many times. This would cause multiple, which could lead to other problems, and also, it's not readable.

@Component({
  selector: 'app-root',
    template: `
      
{{course.shortDescription}}
{{course.longDescription}}
{{course.duration}}
{{course.flags}}
`}) export class AppComponent implements OnInit { course: Course; constructor(private courseService: CourseService) { } ngOnInit() { this.courseService.loadCourse(1) .subscribe(course => this.course = course); } }

Here, .subscribe function call and used for the services we have subscribed to the observable returned by the service layer and defined a local variable and function that includes syntax and output of the back-end call. Now here, our template is a lot simple we only have a variable named course that we can use to access and authorized the data.

But there could be a couple of probable problems with this, mainly in a big application.

Reactive Templates- The Ngif as syntax and the Async pipe:

Though we collect all the available specialty of Ngif with the Async pipe, we can now come up with the following solution:

@Component ({
  selector: 'app-root',
    template: `
    
{{course.shortDescription}}
{{course.longDescription}}
{{course.duration}}
{{course.flags}}
Loading ...
`}) export class AppComponent implements OnInit { courseObs: Observable; constructor(private courseService: CourseService) { } ngOnInit() { this.courseObs = this.courseService.loadCourse(1); } }

So, what is in the example see:

  1. The Async pipe is existing used to subscribe only once to courseObs.
  2. The else clause is defining what to perform time the data is not available.
  3. The 'as' syntax is clear a template variable for the expression courseObs | Async, and That variable is named course there is the component of the template.
  4. Now, there is a local course variable available internal the ngIfsection, that corresponding to the value emitted by the back-end call and other some call that is interoperable.
  5. This course variable is simple to be used, just like if the course object had been passed synchronously as an @Input () decorator to this component.

One-stop oplossing voor Angular-webontwikkeling ?

Uw zoekopdracht eindigt hier.


Advantages of this reactive templates approach

Here are the various advantages of this reactive templates approach:

  1. There are no manual subscriptions at the component level for observable coming out of the service layer of the other layers in these approaches
  2. We don't have to create smaller components to be enabled to use the Async pipe only once and prevent multiple subscriptions
  3. No local data state variables are defined at the level of the component, so it is less likely to run into issues caused by mutable local component state
  4. We now have a more declarative code both the component and the template are much declarative.

Conclusion

As we could look at in this example, the Ngif / else features that are useful in many other ways, are mainly needful when combined with the Async pipe for easy development of Angular applications in a more reactive way. Use RxJS in the specific context of an Angular application where we cover lots of generally used reactive design patterns for building Angular applications.

A simple guide to Build Angular Reactive Templates with Ngif and Async Pipe

Angular Templates seamlessly help to expedite the development process with flawless assistance of components and other specific elements. These are dynamic and renders according to the directive instructions. To put it simply, Angular templates help in developing modern applications with a modest look. In this blog, we will discuss how to build Angular Templates with NgIf and Async pipe.

There are several benefits of writing Angular templates. Some crucial ones are:

  1. Reduced memory usage (depending on the type of Observable we use)
  2. More readable code.
  3. Fewer potential points with multiple subscriptions at the level of the service layer.
  4. Less state in our components.

Overall, this is an excellent way to write readable templates while avoiding by design based problems.

Ngif Else Example in Angular

Let's take a look at the Ngif Else syntax given below as an example:

Condition is true ...

Condition is false ...

We can specify in Ngif an else part with the name of a template, that will change the element where Ngif is put near in case the condition is false.

This will either display Condition is true or the satisfaction of the loading template to the element annotated with Ngif, depends on the truthfulness of the condition.

The Ngif as Syntax in Angular

With Ngif, it is also possible to analyze the truthfulness of an expression and assigning the result of the expression to a variable.

Let's see an example:

@Component ({
  selector: 'app-root',
  template: `
    

{{result.description}}

Condition is false ...

`}) export class AppComponent implements OnInit { course = { id:1, description: 'Angular For Beginners' }; }
  1. The template above would display Angular for startup because the expression course is truthful. As we can see, the course corresponding to a component property which is a simple JavaScript (Type Script) object.
  2. The result of the expression is not a boolean but anything like char, etc. It is an instance and gets assigned to a local template variable named result, and so the description property gets in display to the screen as expected which makes it much simple to write our templates in a different Reactive Style.


Why use the Async pipe?

Because it automatically subscribes and unsubscribes from Observable as the component gets instant or destroyed, which is a big feature.

This is mainly required in the case of long-lived observably like for example exactly Observable returned by the router or via Angular Fire.

In addition, because it makes our programs easier to read and more declarative, with fewer state variables in our component classes.

So, let's use the Async pipe here:

{{(courseObs | async)?.shortDescription}}
{{(courseObs | async)?.longDescription}}
{{( courseObs | async)?.duration}}
{{( courseObs | async)?.flags}}

However, this not very convenient because we need to use the Async pipe many times. This would cause multiple, which could lead to other problems, and also, it's not readable.

@Component({
  selector: 'app-root',
    template: `
      
{{course.shortDescription}}
{{course.longDescription}}
{{course.duration}}
{{course.flags}}
`}) export class AppComponent implements OnInit { course: Course; constructor(private courseService: CourseService) { } ngOnInit() { this.courseService.loadCourse(1) .subscribe(course => this.course = course); } }

Here, .subscribe function call and used for the services we have subscribed to the observable returned by the service layer and defined a local variable and function that includes syntax and output of the back-end call. Now here, our template is a lot simple we only have a variable named course that we can use to access and authorized the data.

But there could be a couple of probable problems with this, mainly in a big application.

Reactive Templates- The Ngif as syntax and the Async pipe:

Though we collect all the available specialty of Ngif with the Async pipe, we can now come up with the following solution:

@Component ({
  selector: 'app-root',
    template: `
    
{{course.shortDescription}}
{{course.longDescription}}
{{course.duration}}
{{course.flags}}
Loading ...
`}) export class AppComponent implements OnInit { courseObs: Observable; constructor(private courseService: CourseService) { } ngOnInit() { this.courseObs = this.courseService.loadCourse(1); } }

So, what is in the example see:

  1. The Async pipe is existing used to subscribe only once to courseObs.
  2. The else clause is defining what to perform time the data is not available.
  3. The 'as' syntax is clear a template variable for the expression courseObs | Async, and That variable is named course there is the component of the template.
  4. Now, there is a local course variable available internal the ngIfsection, that corresponding to the value emitted by the back-end call and other some call that is interoperable.
  5. This course variable is simple to be used, just like if the course object had been passed synchronously as an @Input () decorator to this component.

One-stop oplossing voor Angular-webontwikkeling ?

Uw zoekopdracht eindigt hier.


Advantages of this reactive templates approach

Here are the various advantages of this reactive templates approach:

  1. There are no manual subscriptions at the component level for observable coming out of the service layer of the other layers in these approaches
  2. We don't have to create smaller components to be enabled to use the Async pipe only once and prevent multiple subscriptions
  3. No local data state variables are defined at the level of the component, so it is less likely to run into issues caused by mutable local component state
  4. We now have a more declarative code both the component and the template are much declarative.

Conclusion

As we could look at in this example, the Ngif / else features that are useful in many other ways, are mainly needful when combined with the Async pipe for easy development of Angular applications in a more reactive way. Use RxJS in the specific context of an Angular application where we cover lots of generally used reactive design patterns for building Angular applications.

  • Pin It
TOP