Mostrando entradas con la etiqueta typescript. Mostrar todas las entradas
Mostrando entradas con la etiqueta typescript. Mostrar todas las entradas

viernes, 23 de febrero de 2018

Internationalization in Angular

Here we come again!

Today we will learn how to implement the internationalization in angular easily and in a few steps.

Step 1: Add the necessary libraries to our package.json file.

"dependencies": {
...
"@ngx-translate/core": "8.0.0",
"@ngx-translate/http-loader": "2.0.0",
...
},

Step 2: Configure our application to use a folder of language files.

app.module.ts


import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';


@NgModule({
declarations: [ AppComponent ],
imports: [
...
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
}
})
...
],
providers: [ ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

Step 3: Define a component where you can change the language.

language;

languages: Language[] = [
new Language("ca","CATALÀ"),
new Language("es","ESPAÑOL"),
new Language("en","ENGLISH")
];

constructor(private route: ActivatedRoute,
private translate: TranslateService) {
var userLang = "";
this.route.queryParams.subscribe(params => {
if(!params['lang'] || params['lang'] == "") {
userLang = this.language;
} else {
userLang = params['lang'];
}
console.log("queryParams:" + userLang);

if(!userLang || userLang == "") {
userLang = navigator.language;
}

if(userLang) {
userLang = userLang.toLowerCase();
if(userLang.length > 2) {
userLang = userLang.substring(0, 2);
}
}
if(userLang == "ca" || userLang == "es" || userLang == "en") {
this.changeLanguage(userLang);
} else {
this.changeLanguage("ca");
}
});
}

public changeLanguage(language) {

console.log(language);

// canviar l'idioma per defecte usat a les traduccions
this.translate.setDefaultLang(language);
// canviar l'idioma a usar per fer les traduccions
this.translate.use(language);

// canviem l'idioma seleccionat
this.language = language;
}

@NgModule({
imports: [ ... ],
declarations: [ ... ],
exports: [ ...],
providers: [ TranslateService ]
})

Step 4: Use the Pipe translate to get the translations of the language files.

pageComponent.html

...
{{ 'field' | translate }}
...

Step 5: Create the json files with the translations.

en.json


{
"field": "traduction of my first field"
}

Here we could make all the necessary translations in our pages and components.

If we wanted that when choosing a language, the other components and pages of our application were translated, where we had loaded arrays of information, we should do the following:

Step 1: Subscribe an Observable where to load the array.

projects: Project[];

public static updateStuff: Subject<any> = new Subject();

constructor(
private projectService: ProjectService) {
ProjectsComponent.updateStuff.subscribe(res => {
// here fire functions that fetch the data from the api
this.getProjects();
});
}

ngOnInit(): void {
this.getProjects();
}

getProjects(): void {
this.projectService.getProjects()
.then(projects =>
{ this.projects = projects }
);
}

Step 2: Call the Subscription when we change the language.

import { ProjectsComponent } from '../projects/projects.component';

public changeLanguage(language) {
...
ProjectsComponent.updateStuff.next(false);
...
}

I hope you have helped the tutorial.

Any questions, do not hesitate to ask.

miércoles, 28 de junio de 2017

How to configure Reactive Forms in your Angular Application?

Hey people!

Today I'm going to explain how to configure your Angular application to use Reactive Forms and how to implements your first form.

First of all, you have to install the forms module in your project:

npm install @angular/forms --save

Then, you have to modify your app.module.ts adding:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
imports: [ BrowserModule, ReactiveFormsModule ], 
declarations: [ AppComponent ], 
bootstrap: [ AppComponent ]
})

On this point, your project is prepared for using Reactive Forms.

The you have to modify the form component you want to use:
<div class="container">
  <h1>Add user</h1>
  <form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value, myForm.valid)">
    <div class="form-group">
      <label for="">Name</label>
      <input type="text" class="form-control" formControlName="name">
      <small [hidden]="myForm.controls.name.valid || (myForm.controls.name.pristine && !submitted)" class="text-danger">
            Name is required (minimum 5 characters).
          </small>
      <!--<pre class="margin-20">{{ myForm.controls.name.errors | json }}</pre>-->
    </div>
    <div class="form-group" formGroupName="address">
      <label for="">Address</label>
      <input type="text" class="form-control" formControlName="street">
      <small [hidden]="myForm.controls.address.controls.street.valid || (myForm.controls.address.controls.street.pristine && !submitted)" class="text-danger">
            Street required
          </small>
    </div>
    <div class="form-group" formGroupName="address">
      <label for="">Postcode</label>
      <input type="text" class="form-control" formControlName="postcode">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
    <div class="margin-20">
      <div>myForm details:-</div>
      <pre>Is myForm valid?: <br>{{myForm.valid | json}}</pre>
      <pre>Is myForm submitted?: <br>{{submitted | json}}</pre>
      <pre>myForm value: <br>{{myForm.value | json}}</pre>
    </div>
    <div class="margin-20">
      Form changes:
    </div>
    <div *ngFor="let event of events" class="margin-20">
      <pre> {{ event | json }} </pre>
    </div>
  </form>
</div>
With the typescript file of the component with the changes:

public myForm: FormGroup;
public submitted: boolean;
...

constructor(private _fb: FormBuilder) { }

...

ngOnInit() {

        // the short way
        this.myForm = this._fb.group({
            name: ['', [<any>Validators.required, <any>Validators.minLength(5)]],
            address: this._fb.group({
                street: ['', <any>Validators.required],
                postcode: ['8000']
            })
        });

}

...

save(model: User, isValid: boolean) {
        this.submitted = true;
        console.log(model, isValid);
}

You can develop your forms in many way.
Use which is more easy for you.

Try it and have fun!

lunes, 10 de abril de 2017

How to migrate an Angular 2 Project to Angular 4?

Hi people,

Angular is growing ;) and now we have to migrate it to be updated!

The steps to upgrade to angular 4 are as follows:

First of all verify the Node Version:
> node -v
To actualice the version download it from: https://nodejs.org/en/download/

Then, we are going to actualice angular/cli:

First, we have to remove the actuals possibles versions:
> npm uninstall -g @angular/cli
> npm uninstall -g @angular-cli
Then, we are going to install it again:
> npm install -g @angular/cli
Then, verify the versions installed:
> ng -v
It must shows something like this:
    _                      _                 ____ _     ___ 
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | | 
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | | 
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/                                        
@angular/cli: 1.0.0                                  
node: 6.10.2                                              
os: win32 x64 
Then, goes to the Project directory and actualice the @angular version:

In Windows PC:
npm install @angular/common@next @angular/compiler@next @angular/compiler-cli@next @angular/core@next @angular/forms@next @angular/http@next @angular/platform-browser@next @angular/platform-browser-dynamic@next @angular/platform-server@next @angular/router@next @angular/animations@next --save
In Mac PC:
npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@next --save
In last, actualice typescript version:
> npm install typescript@2.2.1 --save
And finally, start the project:
> ng serve

lunes, 7 de noviembre de 2016

Bind json data to tree component with Angular 2

Here we come again!

Today with news of a useful component that can shows you the way to continue your own components in Angular2.

Here you can see the demo (click the Project link button).

We have two components: the tree component and the node component (the tree component is an array of node components).

Take a look to the tree.component (html and css files):



And here is the ts file:



You can see that we don't need a css file and the html iterate an array of node and calls the app-node-tree with the root properties.

Now take a loot to node.component (html and css files):



Here we can see the styles of my node, setting the div and img style's and the html file. There is a div with the images that we have to load on the node and later we iterate the array of children of the node.

We use a recursive component, because we call the aap-node-tree in an app-node-tree.

Take a look to ts file:



In this Typescript file we load the node with the loadNode method. The ancestors and the property lastNode indicates whether the node is the last sibling of the same parent.

There is a method that change the state between expand and collapse of the image in the node.

At last, we will see the tree.json file with the structure of our tree, that we can change with the structure we want:



On my example, we have to repeat this structure three times and we will get our tree.

I hope you find this article interesting!

Here you can see the example.

This example is done with Angular-cli.

Here you can find the repository of the component done by @davidnezan.

Try it and have fun!

miércoles, 26 de octubre de 2016

Bind json data to html table with Angular 2

Here I come again!

In this example I will show how to bind a JSON file with an html table with Angular2 (the new version of AngularJS, but with Typescript).

Here you can see the demo (click the Project link button).

We need a Service Object and a Component Object and I'm going to use Angular-cli to create them.

First of all, take a look to Service class:

(we will create them with: ng generate service [my.servicename.service])

And I make the next modifications:



The Service returns an Observable of any type, that makes asyncron the call from the Component. So you can extend the code by using any structure of JSON file and making some modifications.

Now I will show you the Component, that we will create with the instruction (ng generate component [componentname.component]):

 

The Component will call our Service and save the information of the JSON file.

Now comes the HTML file and the CSS file:



Here you can see the use of ngFor, the declaration of a variable with "let" and the attribute "async" that makes asyncron our request.

The JSON file will look like this. You can put the attributes you want, but it's important that the HTML file have the sames name of the JSON file's attributes.



And finally, I can show you the structure of the project that has been done with Angular-Cli, as I said in the beginning.



This is my Git Repository where I push this project and you can get it: https://github.com/davidmartinezros/bind-json-array-to-html-table.

Thanks for reading me, I hope it will help you!

Try it and have fun!