ANGULARJS2 Learning Notes (ii) components

Source: Internet
Author: User
Tags emit export class tag name

ANGULAR2 components first understand the meaning of the ANGULAR2 component

The application of ANGULAR2 is the collection of a series of components

We need to create reusable components for reuse by multiple components

Components are nested, and components in real-world applications are nested with each other

Data calls in a component can use inputs and outputs

A component can be an instruction

A component can contain front-end performance and back-end logic

A component can be a code fragment that can run independently

Further understanding of Directives

An instruction is a component

An instruction can be decorated with instructions for changing the DOM

An instruction can be a template directive that can change element

A practical example

A car has a door, a steering wheel, a window, and so on, assuming the car is a parent component, the steering wheel is a subassembly.

In Angular2, the components can be multi-tier, then their communication is the data exchange, this mechanism is the data flow

Data binding in the current ANGULAR2 version is unidirectional, the parent component data is passed to the child component data, and then the child subassembly data is passed

Subcomponents can use event to pass data to the parent component

So we can say there are two ways of data binding

We can make these two kinds of data binding by judging Ngmodel.

Example analysis

Myapp.ts

Import {bootstrap} from ' Angular2/platform/browser ';

Import {carcomponent} from "./car.component";

Bootstrap (carcomponent);

Here we first explain the angular entrance, which is the component we need to start

Here we see first to introduce Bootstrap, to load the components below, and then to introduce the components we need carcomponent, which is the class we want to define below

Car.component.ts

<reference path= ". /node_modules/angular2/typings/browser.d.ts "/>

Import {Component} from ' Angular2/core ';

Import {door} from './door.component ';

@Component ({

Selector: "Cartag",

Template: '

<H3 class= "Titles" >mother Car component

<input type = "text" #textInput bind-value= "text"/>

<button on-click= "Oncarchange (textinput.value)" >Change</button>

<div class= "Child-style" >

<door [textlevel1]= "text" (changed) = "Oncarchange ($event)" >

</door>

</div>

`,

directives: [Door],

Styles:['

. titles {

Color: #0099FF

}

. child-style {

background-attachment:initial; background-size:initial; background-origin:initial; background-clip:initial; background-position:initial; background-repeat:initial; " >}

`]

})

Export Class Carcomponent {

text:string= "Input text";

Oncarchange (value) {

This.text = "Passing Data to subcomponents:" +value;

}

}

Door.component.ts

<reference path= ". /node_modules/angular2/typings/browser.d.ts "/>

Import {Component, eventemitter} from ' Angular2/core ';

@Component ({

Selector: "Door",

Template: '

<input type = "text" #textInput value= "{{textLevel1}}" >

<button (click) = "Ondoorchange (textinput.value)" >Change</button>

`,

Inputs: [' TextLevel1 '],

Outputs: [' changed ']

})

Export Class Door {

textlevel:string;

Changed = new Eventemitter ();

Ondoorchange (value) {

This.textlevel = "Pass data to Parent component:" + value;

This.changed.emit (value);

}

}

}

Car.html

<! DOCTYPE html>

<script>document.write (' <base href= ' + document.location + ' "/> ');</script>

<meta name= "viewport" content= "Width=device-width, initial-scale=1" >

<!--CSS file---

<link href= "Css/bootstrap.min.css" rel= "stylesheet"/>

<!--IE Polyfills, keep the order--

<script src= "Node_modules/es6-shim/es6-shim.min.js" ></script>

<script src= "Node_modules/systemjs/dist/system-polyfills.js" ></script>

<script src= "Node_modules/angular2/bundles/angular2-polyfills.js" ></script>

<script src= "Node_modules/systemjs/dist/system.src.js" ></script>

<script src= "Node_modules/rxjs/bundles/rx.js" ></script>

<script src= "Node_modules/angular2/bundles/angular2.dev.js" ></script>

<script src= "Node_modules/typescript/lib/typescript.js" ></script>

<!--agular 2 Router

<script src= "Node_modules/angular2/bundles/router.dev.js" ></script>

<!--Config Agular 2 and Typescript

<script>

System.config ({

Transpiler: ' Typescript ',

Typescriptoptions: {emitdecoratormetadata:true},

Packages: {' app ': {defaultextension: ' ts '}}

});

System.import (' App/myapp ')

. then (null, Console.error.bind (console));

</script>

<!--Run the application-

<body>

<cartag>loading sample...</cartag>

</body>

Component Reference

First line, current version of the bug, all custom components need to be added under the current version

Component is introduced below, @Companent is an annotated language for typescript, which is used to configure our current component with a number of parameters, which are detailed later.

Introducing the components we need (import)

Component Configuration

First look at selector, the label, which is the tag name we want to use in HTML, similar to the standard HTML tags (such as <div>,

Template: The component's templates, which can be understood as a view of the component, can be used in the template to use the label you just defined, that is, the label name in selector, as you would with standard HTML tags. Here is an inline template that uses a pair of "'" symbols to mark the contents of the template.

In this template you can see that a local variable is defined in the input tag, and ANGULAR2 provides a simple syntax to map an element to a local variable : Add a property that starts with # or var- , and subsequent sections represent  The variable name , which corresponds to an instance of the element. At value of input we see that the value is bound to a property of the Carcomponent component, using the {{}} binding, which is an interpolation binding syntax for angular, another way to use a pair of brackets The properties of an HTML element or component are bound to an expression in the component model, and when the value of an expression changes, the corresponding DOM object is automatically updated as <input type = "Text" #textInput [value]= "text"/> Note that the text after value is a property of Carcomponent, and value is a property of the input object, and there is an expression you can also use the bind-prefix for property binding, such as <input type = "Text" #textInput bind-value= "Text"/>

The template button (click) Represents the event, wraps the event name with a pair of parentheses , and binds to an expression, or you can use the event name with the on- prefix as

<button on-click= "Oncarchange ($event)" >Change</button>

TextInput is a local variable previously defined in input that represents an instance of input, and Oncarchange is a method defined in Carcomponent that receives a parameter, which is used to trigger the Text property change to notify the child component. Of course, you can also define it directly in input, such as

<input type = "text" #textInput bind-value= "text" (change) = "Oncarchange (textinput.value)"/>

The effect is the same.
The template uses the door tag, which is the label we defined in the door component, where textLevel1 and changed are the input and output items defined in the door component

Component Nesting and communication

The use of the door tag in the template in the car assembly means that the door component needs to be added, so that a nested relationship is formed, and the import is first required to introduce the door component import {door} from './door.component ';

In the template we use the door tag of the door component, then we need to configure the directives instruction set

Directives: Instruction set, note is a collection, that is, embedded in the component of multiple components (need to import first), because the above in the template using the door directive, so in the collection must be added door directive

We see templates in car components that use the car component's

<door [textlevel1]= "text" (changed) = "Oncarchange ($event)" >

The door tag is added here, and [TextLevel1] is a property of the door tag, which can be understood as the value property of the input tag, then the definition of this property needs to be added to the inputs in the door component
Inputs: [' TextLevel1 ']
Indicates that the door tag uses TextLevel1 to receive data from the superior, [textlevel1]= "text" means that the Textlevel1 attribute of the door component binds the Text property of the car component, which enables the parent component to pass data to the child component. So how does a child component pass data to the parent component? is to use Outputs,outputs to provide a collection of events that use the events defined by the subcomponents to pass data to the ancestor, as shown in (changed) = "Oncarchange ($event)". (changed) is an event defined by the door component and declared in the outputs configuration, where it is noted that the event handler function of the parent component is called.
Outputs: [' changed ']

$event is the data related to the event, and here is the Textlevel1 the value

Component definition
In order to enable other components to be able to use the component, the component definition and class, using the TYPESCIRPT syntax, the component can be defined properties, methods can be public or private, if it is private need to join the private declaration, It is important to note that if you use an event, you need to introduce eventemitter. such as import {Component, eventemitter} from ' Angular2/core ';
Event definitions Use

Changed = new Eventemitter ();

Use Emit   to pass events such as this.changed.emit (value);
Data interaction of components

Angular2 compared to angular1 there is a big change is the default binding is one-way binding, but also that the data changes on the view can not be directly updated model, need to be programmed to update, the purpose is to improve efficiency, of course, the current version also retains the [ (Ngmodel)] This binding way, you can implement two-way binding. So how do the data between the components pass through each other, Father-〉 son, son-〉 father, son-〉 son?

Parent-to-child data passing

The use of subcomponents in a parent component is simply a way of using the child component label, so that the parent component data is passed to the subassembly by binding one of the subcomponents ' properties to the parent component's property. A simple understanding of

Define a subcomponent in the parent component <child [childproperty]= "Parentproperty" ></child>

This is similar to using <input [value]= "Parentproperty" in the parent component "></input>

In this way the subcomponents are able to get the data of the parent component, and it is important to note that the subcomponents need to advertise the properties used for the binding, that is, using inputs:[' Childproperty ', which is a set of arrays that can advertise multiple properties for external binding.

In summary, you can implement the effect that a parent component passes data to a subassembly by binding a property of the parent component to a property advertised in the child component.

Child-to-parent data passing

The child component passes the data to the parent component through an event, first defining the event in the subcomponent, raising the parent component's event response when the child component's event is triggered, and passing the event arguments to the parent component's response function, thus completing the child component passing the data to the parent component. As shown below

<childlevel1 [parentmsg]= "Parentmsg" (childlevel1changed) = "onchildlevel1msgchanged ($event)" > </ Childlevel1>

[Parentmsg] is a property of a subcomponent, and the value comes from the parent component's parentmsg, which enables the parent component to pass PARENMS data to the subassembly, and (childlevel1changed) is the event defined in the subcomponent. While Onchildlevel1msgchanged is an event response function for the parent component, $event represents the source of the event. From this example we analyze and look at the data stream. The following is the event definition for a subcomponent:

Outputs: [' childlevel1changed ']
<button (click) = "onchildlevel1msgchanged (childlevel1text.value)" >changeChild1</button>
Onchildlevel1msgchanged (event) {
This.childlevel1msg = event;
This.childLevel1Changed.emit (event);
}

The order of events is raised by the button of the child component to the event handler, and the event parameter is Childlevel1text. Value, the event handler broadcasts the event defined by the subcomponent and passes the data source, the parent component detects the child component's event and gives it to the parent component's event handler to process. This passes the child component's data to the parent component.

Child-to-child data transfer

Knowing the way above, then the child to the child is simple, divided into the father, and then the father to the child. Parent component plays a coordinating role in the middle

Finally, see these some doubts, a real application will have a lot of data interaction, if you use this mechanism, it is difficult to maintain the relationship here, there is no better way to implement the data interaction between components? The answer is service!

ANGULARJS2 Learning Notes (ii) components

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.