问题描述:

I am trying to load internal javascript in angular2.

When i click on lable nothing happens.

Here is my code.

 <div class="login-page" style="margin-top:12%">

<div class="form" id="login">

<form class="register-form">

<h3 style="display:inline-block"><span class="glyphicon glyphicon-log-in" ></span></h3> <h1 style="display:inline-block">Sign Up</h1>

<input type="text" placeholder="first name"/>

<input type="text" placeholder="last name"/>

<input type="text" placeholder="email address"/>

<input type="password" placeholder="password"/>

<input type="text" placeholder="mobile"/>

<button>create</button>

<p class="message" (click)="clicked($event)">Already registered? <a href="#">Sign In</a></p>

</form>

<form class="login-form">

<h3 style="display:inline-block"><span class="glyphicon glyphicon-log-in" ></span></h3> <h1 style="display:inline-block">Login</h1>

<input type="text" placeholder="username"/>

<input type="password" placeholder="password"/>

<button>login</button>

<p class="message" (click)="clicked($event)">Not registered? <a href="#" class="message">Create an account</a></p>

</form>

</div>

</div>

 import {Component} from '@angular/core';

@Component({

selector: 'home',

styleUrls: ['./home.css'],

templateUrl: './home.html'

})

export class Home {

clicked(event) {

$('form').animate({height: "toggle", opacity: "toggle"}, "slow");

}

}

Now, in console i am getting this error.

 [default] /var/www/ap/angular2-seed-master/src/app/home/home.ts:10:3

Cannot find name '$'.

Is there any thing wrong. Please suggest me.

网友答案:

Script tags in component templates are just purged without further notice.

You need to use other mechanisms like require() to add scripts to components or add it to index.html directly.

网友答案:

I think you are trying to add javascript code inside component templates. This is not correct way to do it. Instead of it, try to do this using Angular2 way like this :

import { ElementRef } from '@angular/core';
...
constructor(private elementRef : ElementRef) {
}

ngAfterViewInit() {
    jQuery(this.elementRef.nativeElement).find('message').on('click', () => {
    //do something here
    });
}

The ElementRef class is a reference for the component itself in the DOM. So we're able to filter the search to this component.

网友答案:

On p tag add click event. onclick="animateForm()"

In index.html file add the function

<script type="text/javascript">
  function animateForm() {
    alert("click");
      $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
}

</script>
网友答案:

Remember this is TypeScript and not JavaScript. Have you added the Jquery type definition file in your typings?

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/jquery/jquery.d.ts

Or you can refer to this issue. On how to use Jquery with Angular 2

How to use jQuery with Angular2?

相关阅读:
Top