Asked  12 Months ago    Answers:  5   Viewed   196 times

What is the alternative of ng-init="myText='Hello World!'" in Angular 2 to add in the template, not in the component

 <div ng-app="" ng-init="myText='Hello World!'">

the alternative in Angular 2

 Answers

5

You can use a directive

@Directive({
  selector: 'ngInit',
  exportAs: 'ngInit'
}) 
export class NgInit {
  @Input() values: any = {};

  @Input() ngInit;
  ngOnInit() {
    if(this.ngInit) { this.ngInit(); }
  }  
}

you can use it to pass a function to be called like

<div [ngInit]="doSomething"

or to make values available

<div ngInit [values]="{a: 'a', b: 'b'}" #ngInit="ngInit">
  <button (click)="clickHandler(ngInit.values.a)">click me</button>
</div>
  • ngInit addes the directive
  • [values]="{a: 'a', b: 'b'}" sets some initial values
  • #ngInit="ngInit" creates a reference for later use
  • ngInit.values.a reads the a value from the created reference.

See also Converting Angular 1 to Angular 2 ngInit function

Thursday, June 24, 2021
 
hnkk
 
2

Thats kinda tricky to explain:

Date is a class, this means that values of type Date need to be created through a constructor call. In other words, create a class instance with new Date(...).

The Response.json method will only return an object in JSON format, and such doesnt contain an instance of any class, only maps of key:property.

So what you need to do, is to manually convert the value returned from .json() to a Base object. This can be done as follows:

public getSingle = (keys: any[]): Observable<Badge> => {
        return this._http.get(this.actionUrl + this.getKeysUrl(keys))
            .map(r => r.json())
            .map(v => <Badge>{
              badgeNumber: v.badgeNumber,
              authorizationLevel: v.authorizationLevel,
              endOfValidity: new Date(v.endOfValidity)
              // preferably this string should be in ISO-8601 format
             })
            //the mapping step can be done in other ways most likely
            .catch(this.handleError);
}
Saturday, June 26, 2021
 
EastSw
 
2

The error is very clear and specific

Error: Cannot call a namespace ('moment') at error (/Users/chris/angular-library/node_modules/rollup/dist/rollup.js:185:14)

This is per the ES Module Specification.

That means the following is an invalid way to import moment, or anything you intend to call, because a module namespace object, such as that created by * as ns may not be called.

import * as moment from 'moment';

The correct form is the form that ngc is raising an error on

import moment from 'moment';

Firstly to make this work, you need to specify the --allowSyntheticDefaultImports flag.

tsconfig.json

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true
  }
}

Assuming that ngc will recognize the option, you still have an additional problem to work out.

The flag above is for users of tools such as SystemJS or Webpack which perform the synthesis, allowing such code to typecheck.

As of TypeScript 2.7, you can now specify the --esModuleInterop flag to have the language provide the synthesis as part of the transpilation process.

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  }
}

Note that if you are using a version of TypeScript prior to 2.7 and if you are compiling to CommonJS, AMD, or UMD modules (e.g. with --module commonjs) the correct import syntax is rather

import moment = require('moment');

The import = require syntax is a TypeScript specific construct, now largely unnecessary. It exists to acquire both the type and the value of the module exports of an AMD, CommonJS, or UMD module. The "and" is important because a const, var, or let = require invocation only creates a name in the value space not in the type space.

Wednesday, August 4, 2021
 
2

Could not find native solution, but you can use (ngModelChange) and then get the parsed value like this:

  parseTextArea() {
     this.textareaParsed = this.textarea.split("n");
  }

and in your template:

<textarea [(ngModel)]="textarea" (ngModelChange)="parseTextArea()"></textarea>

See this plunker: textarea example (in Chrome, IE has some issues with config.js...)

Friday, August 6, 2021
 
palAlaa
 
3

ng-init is supposed to work like this, because it's used to initialize data.

A very simple example:

<ul ng-init="list = [1,2,3,4]">
  <li ng-repeat="l in list"></li>
</ul>

If you are trying to run something while your controller loads, it's actually much simpler than you thought:

app.controller('mainCtrl', function ($scope) {

  var init = function ($scope) {
    // do whatever you need to do to initialize your controller
    $scope.someData = ["Hey", "I'm", "Alive"]
    $scope.otherData = localStorage.getItem('myBackup')
  }

  init()

})

Or even simpler, if you don't need the function (no closures or whatever)

app.controller('mainCtrl', function ($scope) {

  // do whatever you need to do to initialize your controller
  $scope.someData = ["Hey", "I'm", "Alive"]
  $scope.otherData = localStorage.getItem('myBackup')

})

Edit - assuming you're using ngView:
To have the code run on when the page is fully loaded you should set a watcher on the event $viewContentLoaded, like this:

  $scope.$on('$viewContentLoaded', function(){
    //Here your view content is fully loaded !!
  });

app.controller('mainCtrl', function ($scope) {

  // This event is triggered when the view has finished loading
  $scope.$on('$viewContentLoaded', function() {

    $scope.someData = ["Hey", "I'm", "Alive"]
    $scope.otherData = localStorage.getItem('myBackup')      

  })    
})
Friday, October 8, 2021
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :