Basics V1 Flashcards

1
Q

How to “select” elements which aren’t valid as yet to apply specific styling?

A

You can follow this pattern for example:

input.ng-invalid {
border: 1px solid red;
}

select.ng-invalid {
border: 1px solid red;
}

Notice we are appending .ng-invalid to the specific elements otherwise without the specific elements at the beginning all elements will have the styles applied.

input.ng-invalid.ng-touched {
border: 1px solid red;
}

With .ng-touched included, styles won’t be applied until after the user has “touched” the element and it’s still in an invalid state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to show validation message specific to an element?

A
< input 
    class="form-control" 
    id="email" 
    name="email" 
    ngmodel
    required
    type="email" 
    #email = "ngModel"
/>

< span
class=”help-block” *ngIf=”!email.valid”>
Please enter a valid email!
< /span >

Notice the reference #email is assigned by the ngModel

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to apply a default value to a form control/element?

A
//Template
< select 
      id="secret" 
      class="form-control" 
      [ngModel]="defaultQuestion" 
      name = "secret" 
>
//Component
// we just define a variable.
defaultQuestion = "Name of pet?"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Once routing is set up, how to activate?

A

place in the component where routing is set up, which will activate routing for it’s children.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Using Angular router, how to apply an active class to each menu item?

A

place routerLinkActive=”active” on the parent tag of the links.
eg.

< ul class="nav navbar-nav" > 
   < li routerLinkActive="active" >
     < a routerLink = "/recipes" >Recipes< /a>
   < /li> 
  < li routerLinkActive="active">
     < a routerLink = "/shopping" >Shopping< /a>
  < /li> 
< /ul>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

With anchor tags and utilising angular routing, what do you need to make sure of?

A

href’s are removed on the anchor tag and to make sure that style=”cursor:pointer;” is placed on the parent elementto give the hand feature on the link.
eg.

< a class=”list-group-item” style=”cursor:pointer” *ngFor=”let ingredient of ingredients” >

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Get a route parameter passed in once only.

A
ngOnInit(): void {
 const id = this.route.snapshot.params['id'];
}

…and don’t forget to inject the ActivatedRoute in through the constructor to gain access to route.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Listen for anytime a new route parameter is passed in and react to those changes.

A
ngOnInit(): void {
   const id = this.route.params.subscribe( (params:Params) =>  { this.id = +params['id'] } )
}
...and don't forget to inject the ActivatedRoute in through the constructor to gain access to route.
// the + is parsing the value to an int.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

With Angular router, what do you need to do to routerLink if you want to bind dynamic segment in the path?

A

need to put it in array syntax. eg. [routerLink] = “”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

For parent to child, when passing values via components, what’s the rule to remember?

A

Left is receiving component, right is value passed in… And if you bind it, you don’t need to “pass” it in via a constructor or set it on ngOnInit.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

With routing, does the order in which you define the routes matter?

A

Yes!

As below, if new was placed below the :id route, then angular would be confused if you went recipes/new. But if it’s above, then you can go recipes/new without any worries.

{ path: ‘recipes’, component: RecipesComponent, children: [
{ path: ‘’, component: RecipeUnselectedComponent },
{ path: ‘new’, component: RecipeEditComponent },
{ path: ‘:id’, component: RecipeDetailComponent },
{ path: ‘:id/edit’, component: RecipeEditComponent }
] }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you prevent memory leaks with observables?

A

Use the Subscription in memory method.
Meaning define your subscription to a variable at the top then use it where you need.

NOTE: Don’t need to do this for observables provided by the angular package or features of angular.

ANOTHER NOTE: Ensure you’re including the right things in ngOnDestroy also.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

When working with observables, when would you include .pipe(map(data) => {}) or any other operator which would change the format of the data that you want to receive.

A

Before calling the .subscribe method on it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What was the traditional way to emit events across components ?

A

Using a service with eventEmitter where the service has the EventEmitter and the receiving component subscribes to it.

eg in Service.
// definition
ingredientsChanged = new EventEmitter();
// emission
this.ingredientsChanged.emit(this.ingredients.slice());
eg in Receiving Component
// service injected into constructor

constructor(private slService: ShoppingListService) { }

// subscribe to service
this.slService.ingredientsChanged.subscribe((ingredients: Ingredient[]) => 
  { this.ingredients = ingredients; });
// displaying in the template of receiving component
{{ingredient.name}} ({{ingredient.amount}})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the new way / recommended way to emit events across components?

A

Using subjects.

eg in Service
// definition
ingredientsChanged = new Subject();
// emission - notice the .next call instead of .emit
this.ingredientsChanged.next(this.ingredients.slice());
// subscribe to service
this.slService.ingredientsChanged.subscribe((ingredients: Ingredient[]) => 
  { this.ingredients = ingredients; });
// displaying in the template of receiving component:
{{ingredient.name}} ({{ingredient.amount}})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does a “control” refer to in the context of Angular forms

A

It refers to what is in the JS object which Angular creates as a representation upon detecting the element.

NOTE: not all elements within the form are “controls”, only what is inside the hidden JS object.

17
Q

Whats a good way to think about how Angular handles a TD form?

A

When Angular detects a element, it creates a Javascript representation of that form which can’t be seen.

Angular will not automatically detect changes within the form.

18
Q

With a TD form, how do you specify which elements/inputs you want as controls in the form. eg. which elements do you want included in the JS representation of the form?

A

Include ngModel (alone) and a name such asname=”username” on the element.

// example
< input type="text" id="username" class="form-control" ngModel name="username" >
19
Q

How do you make an Angular TD form submittable? (the non-ViewChild way)

A

To the form element in the template, add: (ngSubmit)=”onSubmit()”

// Example implementation:
< form (ngSubmit)="onSubmit()" >

In the .ts file (code behind) you’d obviously have the onSubmit function defined. This is how Angular takes advantage of the original way forms are submitted.

//eg in your component
onSubmit(form: NgForm){
   console.log(this.signupForm);
}
20
Q

How do you pass through the form data when a user submits a form?

A
//Add a reference on the form element and then pass it in eg.
< form (ngSubmit)="onSubmit(f)" #f >
//Then you can receive it in the .ts file with the following:
onSubmit(form: HTMLFormElement) {
   console.log("Submitted");
}

If you want to go even further you can use this trick assigning #f by ngForm which provides access to the JS representation of the form.

< form (ngSubmit)=”onSubmit(f)” #f=”ngForm” >

eg. The values from the form then will be found on the value property of that NgForm object.

21
Q

How does navigating programatically work?

A
// Template
< button class="btn btn-primary" (click)="onLoadServer()">Load Server 1
//Inject in the component constructor
(private router : Router){ }
//Component
onLoadServer(){
   this.router.navigate(['/servers']);
}

Remember that by default the router.navigate method does not know which route the user is on. The routerLink always knows in which component/route it sits.

22
Q

Angular router: Relative path vs Absolute path

A

// The slash is the difference.
Relative path: [‘servers’]
Absolute path: [‘/servers’]

23
Q

How do you change the default for the this.router.navigate method to ensure it knows in which component it sits (by default it doesn’t know)

A
//Inject in the component
  constructor(private serversService: ServersService,
              private router: Router,
              private route: ActivatedRoute) {
  }
// NOTE: ActivatedRoute injects the current route into the
// component.
constructor(private router : Router, private route: ActivatedRoute){ }
//Method
// 1. notice the additional relativeTo property
// 2. notice the path is relative, eg. no slash in path.
//3. notice the route injected above passed here

onLoadServers(){ this.router.navigate([‘servers’], {relativeTo: this.route }) }

24
Q

How do you pass a parameter into a path using Angular router?

A
'users/:id'
// The colon ':' tells angular that this part will be a dynamic part of the path.

// NOTE: this allows you to encode data into your path. Then to receive it, you can use a snapshot (single receive) or a route observable (multiple receive)

25
Q

How would you pass multiple parameters in your route path and receive those?

A

//pass it like ‘users/:id/:name’

// receive like
const id = this.route.snapshot.params['id']; 
const name = this.route.snapshot.params['name'];

//OR receive with object for example.

const user = { id: this.route.snapshot.params['id'], 
               name: this.route.snapshot.params['name']; 
}

//NOTE: route comes from ActiveRoute which is to be injected into the constructor of the receiving component.

26
Q

Angular doesn’t re-create component if user is already on the component and routes to the same component? True or False?

A

True

27
Q

How do queryParams work with Angular routes?

A
//Template calling the route..
      < a
        [routerLink]="['/servers', server.id]"
        [queryParams]="{allowEdit: server.id === 3 ? '1' : '0'}"
        fragment="loading"
        class="list-group-item"
        *ngFor="let server of servers">
        {{ server.name }}
//Component
  ngOnInit() {
    this.route.queryParams
      .subscribe(
        (queryParams: Params) => {
          this.allowEdit = queryParams['allowEdit'] === '1' ? true : false;
        }
      );
28
Q

How to set up a page not found. ie redirection and catching different URLs.

A

{ path: ‘**’, redirectTo: ‘/not-found’ } // ** means catch all paths you don’t know // redirectTo, redirects users to the not-found component.

You also need to ensure that the component you’re redirecting users to is “registered”.

As below, the not-found component is registered, so we can use it in our redirection.

const appRoutes: Routes = [
  { 
    path: 'not-found', 
    component: ErrorPageComponent, 
    data: {message: 'Page not found!'} 
  },
  { path: '**', redirectTo: '/not-found' }
];
29
Q

What’s important to know about when using router redirection?

A

In our example, we didn’t encounter any issues when we tried to redirect the user. But that’s not always the case when adding redirections.

By default, Angular matches paths by prefix. That means, that the following route will match both/recipes and just/

{ path: ‘’, redirectTo: ‘/somewhere-else’ }

Actually, Angular will give you an error here, because that’s a common gotcha:This route will nowALWAYSredirect you!Why?

Since the default matching strategy is”prefix”, Angular checks if the path you entered in the URLdoesstart with the pathspecified in the route. Of course every path starts with’’ (Important:That’s no whitespace, it’s simply “nothing”).

To fix this behavior, you need to change the matching strategy to”full”:

{ path: ‘’, redirectTo: ‘/somewhere-else’, pathMatch: ‘full’ }

Now, you only get redirected, if the full path is’‘(so only if you got NOother content in your path in this example).

30
Q

Which Validators do ship with Angular?

A

Angular forms has a valid property on the JS representation of the form and each individual control has a valid property

Check out the Validators class: https://angular.io/api/forms/Validators - these are all built-in validators, though that are the methods which actually get executed (and which you later can add when using the reactive approach).

For the template-driven approach, you need the directives. You can find out their names, by searching for “validator” in the official docs: https://angular.io/api?type=directive - everything marked with “D” is a directive and can be added to your template.

Additionally, you might also want to enable HTML5 validation (by default, Angular disables it). You can do so by adding the ngNativeValidate to a control in your template.

31
Q

How to disable elements if the form is not valid?

A

You can disable elements as follows where #f is the form reference.

< button class=”btn btn-primary” type=”submit” [disabled] = “!f.valid”>Submit < /button >

32
Q

How to show validation message specific to an element?

A

You can follow this pattern for example:

input.ng-invalid {
border: 1px solid red;
}

select.ng-invalid {
border: 1px solid red;
}
Notice we are appending .ng-invalid to the specific elements otherwise without the specific elements at the beginning all elements will have the styles applied.

input.ng-invalid.ng-touched {
border: 1px solid red;
}
With .ng-touched included, styles won’t be applied until after the user has “touched” the element and it’s still in an invalid state.

33
Q

How to apply a default value to a form control/element?

A
//Template
< select id="secret" class="form-control" [ngModel]="defaultQuestion" name = "secret" >
//Component
// we just define a variable.
defaultQuestion = "Name of pet?"
34
Q

In an Angular form, how to use ngModel with two way binding?

A

< textarea name=”questionAnswer” rows=”3” [(ngModel)]=”answer” class=”form-control”>
…and the “answer” above is a variable defined on the component.

This is for when you want to instantly react to change or something. You want the values at all times.. eg. repeating what the user has entered.

35
Q

How do you “group” form controls with Angular?

A

You can add ngModelGroup to the parent element of the multiple controls you want to group.

The “userData” string assigned to the ngModelGroup below becomes the name of the property that contains the form controls on the JS object which represents the form.

< div id=”user-data” ngModelGroup=”userData” >

36
Q

How to apply validation on form control group?

A

// Ensure to add this on the parent div: #userData=”ngModelGroup”

// As shown below
< div id="user-data" ngModelGroup="userData" #userData="ngModelGroup" >
// Then you can show or hide elements based on it.
< p *ngIf="!userData.valid &amp;&amp; userData.touched">User data is invalid< /p >
37
Q

How to use form data with TD forms?

A
onSubmit(form: NgForm){
    this.user.username = this.signupForm.value.userData.username;
    this.user.email = this.signupForm.value.userData.email;
    this.user.secretQuestion = this.signupForm.value.secret;
    this.user.answer = this.signupForm.value.questionAnswer;
    // this.user.gender = this.signupForm.valid.gender;
  }
38
Q

How to reset a TD form?

A
// Component
this.signupForm.reset();

// This action will reset all values and clear data.

// NOTE: You can also pass in setValue() to the reset() function to set form values to something specific.