Michio JP

Michio JP

1568436032

How to use ViewChild and ViewChildren in Angular

A component can obtain a reference to an element or directive so we can access it directly. The directive can be either Angular’s own or a user-defined custom directive. We can sometimes require access to the element or component directly and manipulate the properties of the component or element. This is somehow the same as getting a DOM element using JavaScript and updating the property and behavior of the DOM element.

Working With Angular’s ViewChild

@ViewChild can be used to get the reference of the DOM element rendered inside an Angular component. We can use the reference of the DOM element to manipulate element properties. To get the component, we need to specify the selector.

// Accessing DOM element with JavaScript
let domReference = document.getElementById("someElement");

// Access DOM element using Angular @ViewChild
@ViewChild(“someElement”) domReference;

Access this code here

Given above is the code to access the DOM element using either plain JavaScript or Angular’s @ViewChild. Using JavaScript, we can use a selector to extract the component. Given our statement below, we are trying to access the element using an element ID.

<div id=”someElement”>Sample Code</div>

Given below is a div element having a template reference marked as someElement. Template references start with #. In the case of Angular, we can access the elements using these template references. The element reference can be retrieved by using @ViewChild and the template-reference variable specified for the same. Let’s look at this in action.

<div #someElement>Sample Code</div>

When Can We Refer to This ViewChild Variable?

The reference to a @ViewChild variable is assigned once the View has been initialized. Angular provides a life-cycle Hook called ngAfterViewInit, which is called once the View has been initialized. Once the View is initialized and rendered, the @ViewChild can then access the element using the template reference. It provides us with access to the element/directive.

Let’s look at the code:

@Component({
selector: ‘accessing-template-reference’,
template: ‘<div><input type=“text” #someElement />’
})
export class HeroListComponent implements OnInit {
@ViewChild(“someElement”) domReference;

ngAfterViewInit(): void {
this.domReference.nativeElement.focus();
}
}

Access this code here

In the code above, the following points need to be considered:

1.    We can access the input element having the template-reference variable “someElement” using @ViewChild.

2.  The ViewChild element domReference will receive access to the DOM element only after it has been rendered. Once the component is rendered, a life-cycle event called ngAfterViewInit is invoked. So we can refer to the element in this life-cycle event or in later life-cycle events.

3.  @ViewChild can enable the user to access the native DOM element of the View rendered. Using this DOM reference, we can access and modify DOM properties like manipulating style, innerText, value, and other properties related to an element referred.

4.  We are directly accessing the DOM, so we are tightly coupled with the browser. So we may not be able to use these references using server-side rendering, and it also may pose security threats.

Accessing Element Using Angular Directive

We can use Angular directives like NgModel with @ViewChild. Let’s look for the requirement and use case scenarios for accessing Angular directives using @ViewChild.

@Component({
selector: ‘accessing-template-reference’,
template: &lt;div&gt; &lt;input type="text" id="userName" [(ngModel)]="userName" /&gt; &lt;/div&gt;
})
export class HeroListComponent implements OnInit {
@ViewChild(NgModel) userNameReference: NgModel;

ngAfterViewInit(): void {
this.userNameReference,valueChanges.subscribe(
() => { this.executeOtherFunction() }
)
}
}

Access this code here

We can access the NgModel directive inside @ViewChild and subscribe to value changes. Given above is the code, where we are trying to access an element using the Angular Directive NgModel. Element with the ID userName is having the directive NgModel added to it. Using @ViewChild, we will track changes to any value update inside the input element.

We get the reference to the input element’s NgModel data structure, and using reference, we can access its state information, like whether it has been modified or if the value is valid or not.

It can be accessed inside the ngAfterViewInit life cycle. We get access to all the state information. It also provides information about any updates to the property. This reference is read-only. It gives us access to observable, and we can use this observable to subscribe to the valueChanges observable.

Whenever the value is updated, a callback function associated with it is triggered, and we can add custom logic in response to the update.

Working With Angular’s ViewChildren

Working with @ViewChildren is similar to @ViewChild, but the difference between the two is @ViewChildren provides a list of element references rather than returning a single reference. It is used to reference multiple elements. We can then iterate the list of the element referenced by the variable.

The following selectors can be used with @ViewChildren:

1. We can use ViewChildren with Angular directives like NgModel

We can use inbuilt directives like NgModel with ViewChild. It will give the list of all the elements having the directive NgModel attached to it.

@Component({
selector: ‘accessing-template-reference’,
template: &lt;div&gt; &lt;input type="text" [(ngModel)]="userName" /&gt; &lt;input type="text" [(ngModel)]="userAge" /&gt; &lt;input type="text" [(ngModel)]="userDesignation" /&gt; &lt;/div&gt;
})
export class HeroListComponent implements OnInit {
@ViewChildren(“NgModel”) domReference: QueryList<NgModel>;

ngAfterViewInit(): void {
console.log("Element List: " + this.domReference.length);
}
}

View this code here

Given above is the code, which extracts the element using the Angular directive NgModel. All the components containing the specified Angular directive can be retrieved and further evaluated.

2. Accessing elements using child components

Similar to the usage of directives with @ViewChildren, we can use the child component name to access the elements using @ViewChildren. This just necessitates that we have some child component (e.g., user-details) inside our main component. Let’s see the following scenario with an example.

@Component({
selector: ‘accessing-template-reference’,
template: &lt;div&gt; &lt;user-details [userId]="firstUser"&gt;&lt;/user-details&gt; &lt;user-details [userId]="secondUser"&gt;&lt;/user-details&gt; &lt;user-details [userId]="thirdUser"&gt;&lt;/user-details&gt; &lt;/div&gt;
})
export class HeroListComponent implements OnInit {
@ViewChildren(“UserDetailComponent”) userDetailReferences: QueryList<NgModel>;

ngAfterViewInit(): void {
console.log("Element List: " + this.userDetailReferences.length);
}
}

View this code here

The code above gets the list of all the child-component references contained inside a parent component.

We can then use these references to accomplish custom logic. The developer can then use this list to accomplish further tasks.

3. Using template-reference variables

Multiple components inside the element can contain the same template reference. If we use a template reference in multiple places, we receive the reference list of all components referred by the same template-reference variable in the template.

@Component({
selector: ‘accessing-template-reference’,
template: &lt;div&gt; &lt;input type="text" #applicationInfo /&gt; &lt;input type="text" #applicationInfo /&gt; &lt;input type="text" #applicationInfo /&gt; &lt;/div&gt;
})
export class HeroListComponent implements OnInit {
@ViewChildren(“applicationInfo”) applicationInfo: QueryList<NgModel>;

ngAfterViewInit(): void {
console.log("Element List: " + this.applicationInfo.length);
}
}

View this code here

The code above contains multiple components with the same template-reference variable. @ViewChildren will enable the user to access all the components that refer to the template reference applicationInfo.

4. Accessing multiple template-reference variables

The selector can be a set of template references. We can specify multiple template references. All the components containing the template reference specified in the list are retrieved from the component.

@Component({
selector: ‘accessing-template-reference’,
template: &lt;div&gt; &lt;input type="text" #userName /&gt; &lt;input type="text" #userAge /&gt; &lt;input type="text" #userDesignation /&gt; &lt;/div&gt;
})
export class HeroListComponent implements OnInit {
@ViewChildren(“userName, userAge, userDesignation”) userInfoReference: QueryList<NgModel>;

ngAfterViewInit(): void {
console.log("Element List: " + this.userInfoReference.length);
}
}

View this code here

In the code above, we are adding the list of template-reference variables inside @ViewChildren. All the components containing the element reference contained in the list are retrieved and can be accessed with the variable name.

Working with ViewChild and Child Components

ViewChild and ViewChildren can be used to access the properties and methods of the child component. Using ViewChild and ViewChildren, we can get the reference of the child component, which further gives access to all the properties and methods. This can enable a parent component to access the child component and enable communication between them.

Let’s look at the code to understand the concept better:

@Component({
selector: ‘child-component’,
template: &lt;div&gt; &lt;input type="text" [(ngModel)]="userName" /&gt; &lt;/div&gt;
})
export class ChildComponent implements OnInit {

public userName: string;

updateUserName(): void {
this.userName = “Mayank”
}
}

View this code here

The code above contains a simple child component, which has the property userName and the function updateUserName, prescribed to update the userName property of the component.

Now let’s add a new component that will act as a parent component for the above ChildComponent. We will look into the code to access the child component’s properties and methods from the parent component using @ViewChild. Let’s look at the code below.

@Component({
selector: ‘child-component’,
template: &lt;div&gt; &lt;b&gt;This is the Parent Component Accessing Child Component&lt;/b&gt; &lt;child-component #userInformation&gt;&lt;/child-component&gt; &lt;input type="button" value="Update User Name" (click)="updateUserData()" /&gt; &lt;/div&gt;
})
export class ParentComponent implements OnInit {
@ViewChild(“userInformation”) childComponentReference: any;

updateUserData() {

// Accessing Property of Child Component
this.childComponentReference.userName = "Updated Name";

// Accessing Functions of Child Component
this.childComponentReference.updateUserName();

}
}

View this code here

The above code represents a parent component. In the template specified for the parent component, we have a child component added.

The child component is marked with a template-reference variable. We can use this template reference to access the properties and variables of the child component.

@ViewChild(“userInformation”) childComponentReference: any;

@ViewChild can be used to access the child component having the template reference userInformation, which represents the child component. Using this childComponentReference, we can further access the properties and call the function of the child component, as specified above.

Conclusion

I hope the article was informative for you. Feel free to leave a comment below.

Originally published by Mayank Gupta at medium.com

============================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Angular 8 Pagination Example and Tutorial

Angular 8 + Spring Boot 2.2: Build a CRUD App Today!

Angular 8 Forms Tutorial - Reactive Forms Validation Example

Angular 8 Tutorial By Example: (REST API, HttpClient GET, Components, Services & ngFor)

#angular #web-development

What is GEEK

Buddha Community

How to use ViewChild and ViewChildren in Angular
Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Ayyaz Zafar

1624138795

Angular Material Autocomplete - Multiple Use Cases covered

Learn How to use Angular Material Autocomplete Suggestions Search Input. I covered multiple use cases.

Please watch this video. I hope this video would be helpful for you to understand it and use it in your projects

Please subscribe: https://www.youtube.com/channel/UCL5nKCmpReJZZMe9_bYR89w

#angular #angular-material #angular-js #autocomplete #angular-material-autocomplete #angular-tutorial

Roberta  Ward

Roberta Ward

1593184320

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.

Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.

We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.

What is a Component in Angular?

Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
})

Role of App Module

Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.

@NgModule({
declarations: [
  AppComponent,
],
imports: [
  BrowserModule,
  HttpClientModule,
  AppRoutingModule,
  FormsModule
],
bootstrap: [AppComponent]
})

What is Data Binding?

Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:

  • When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”.
  • When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”.
  • When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”.

image for understanding data binding

#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular

Clara  Gutmann

Clara Gutmann

1599459851

Angular Sass: How To Use Sass In Angular 9 Tutorial

Angular supports Sass, CSS, and Less to style global application styles as well as component styles. Angular components styles have an effective CSS encapsulation mechanism that assures any component CSS is local to the component and does not globally alter any styles.

Angular Sass Example

Why use Angular Sass? Well!! Sass (Syntactically Awesome Style Sheets) is an extension of CSS that allows you to use things like variables, nested rules, inline imports, and more. It also supports you to keep things organized and enables you to create style sheets faster.

In short,  Sass is a CSS preprocessor, which combines unique features such as variables, nested rules, and mixins (sometimes referred to as syntactic sugar) into regular CSS. The main object of Sass is to make the CSS coding process more comfortable and more efficient.

Sass is compatible with all versions of CSS. When working with the Angular CLI, the default stylesheets have the .css extension. We are using Angular CLI 8. So, if you have not used previously, then please upgrade your  CLI version. We will use the Bootstrap 4 Framework for this demo and see how we can configure the Sass in our Angular 9 application.

#angular #angular 9 #angular cli #css #angular sass

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website