I am using angular-cli to create a new Angular 2 project. I am trying to add a js library kinto.
However Angular 2 use typescript, and kinto is a js library, when i want to import it , Angular doesn't detect kinto.js which is in my node_modules.
I tried to directly import it in my index.html and it doesn't work
app.component.ts
import { Component } from '#angular/core';
import { EnvComponent } from "./env/env.component"
import { Kinto } from "../../node"
// Routage
import { ROUTER_DIRECTIVES } from '#angular/router';
#Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
directives: [ROUTER_DIRECTIVES, EnvComponent]
})
export class AppComponent {
constructor(){
}
}
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ModuleApp</title>
<base href="/">
{{#unless environment.production}}
<script src="/ember-cli-live-reload.js" type="text/javascript"></script>
{{/unless}}
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="vendor/materialize-css/dist/css/materialize.css">
<link rel="stylesheet" href="styles.css">
<script src="../node_modules/requirejs/require.js"></script>
</head>
<body>
<header>
<img src="app/ressources/img/INTESENS-logo-site-internet.png" alt="">
</header>
<app-root>
<div class="preloader-wrapper big active" id="loader">
<div class="spinner-layer spinner-green-only">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="gap-patch">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
</div>
</app-root>
{{#each scripts.polyfills}}
<script src="{{.}}"></script>
{{/each}}
<script src="../node_modules/kinto/dist/kinto.js"></script>
<script>
System.import('system-config.js').then(function () {
System.import('main');
}).catch(console.error.bind(console));
</script>
</body>
</html>
system.config.ts
/***********************************************************************************************
* User Configuration.
**********************************************************************************************/
/** Map relative paths to URLs. */
const map: any = {
};
/** User packages configuration. */
const packages: any = {
};
////////////////////////////////////////////////////////////////////////////////////////////////
/***********************************************************************************************
* Everything underneath this line is managed by the CLI.
**********************************************************************************************/
const barrels: string[] = [
'materialize-css',
// Angular specific barrels.
'#angular/core',
'#angular/common',
'#angular/compiler',
'#angular/forms',
'#angular/http',
'#angular/router',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
// Thirdparty barrels.
'rxjs',
// App specific barrels.
'app',
'app/shared',
'app/module',
'app/env',
/** #cli-barrel */
];
const cliSystemConfigPackages: any = {};
barrels.forEach((barrelName: string) => {
cliSystemConfigPackages[barrelName] = { main: 'index' };
});
/** Type declaration for ambient System. */
declare var System: any;
// Apply the CLI SystemJS configuration.
System.config({
map: {
'#angular': 'vendor/#angular',
'rxjs': 'vendor/rxjs',
'main': 'main.js',
'materialize' : 'vendor/materialize-css'
},
packages: cliSystemConfigPackages
});
// Apply the user's configuration.
System.config({ map, packages });
Thanks for your Help !
Related
I am learning Angular by following a book and i came to a task where i have to implement a rating component using bootstrap.When i compile my code, the rating component doesn't appear and I couldn't find the mistake...
rating.component.ts
#Component({
selector: "rating",
template:`<i
class="glyphicon"
[class.glyphicon-star-empty]="rating < 1"
[class.glyphicon-star]="rating >= 1"
(click)="onClick(1)"
>
</i>
`
})
export class RatingComponent{
rating = 0;
onClick(ratingValue:any){
this.rating = ratingValue;
}
}
app.component.ts
#Component({
selector: 'app-root',
template: `
<rating></rating>`,
})
export class AppComponent {
title = 'Angular Project';
}
index.html
<html lang="en">
<head>
<meta charset="utf-8" />
<title>MyApp</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css"
integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx"
crossorigin="anonymous"
/>
</head>
<body>
<app-root></app-root>
</body>
</html>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ProductsComponent } from './Components/product.component';
import { AppComponent } from './app.component';
import { AdvertisementComponent } from './Components/advertisement.component';
import { MaterialComponent } from './Components/material.component';
import { RatingComponent } from './Components/rating.component';
#NgModule({
declarations: [
AppComponent,ProductsComponent,AdvertisementComponent,MaterialComponent,RatingComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
You're trying to use glyphicon in Bootstrap5, it was discontinued in Bootstrap4.
If you really want to use glyphicon and if working with an older version of Bootstrap it's not a problem, you can use Bootstrap3 changing the index.html file
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#3.4.1/dist/css/bootstrap.min.css"
/>
Your code is displaying only one star, you can show 5 stars changing the template to something like:
<span *ngFor="let number of [1, 2, 3, 4, 5]">
<i
class="glyphicon"
[class.glyphicon-star-empty]="rating < number"
[class.glyphicon-star]="rating >= number"
(click)="onClick(number)"
>
</i>
</span>
I have a new Angular project that I built with:
ng new "app-name"
I'm trying to use the ngTagsInput for a tag input box but every time I build and run my app I get an error in my browser console saying:
ReferenceError: angular is not defined
It looks like it's coming from the ng-tags-input.js. What's going on with this thing?
Edit: I've also tried using
npm install ng-tags-input#3.2.0 --save
and then in my app.module.ts using
import { NgTagsInput } from 'ng-tags-input';
That didn't seem to work either.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example Title</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="assets/materialize.min.css">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="assets/ng-tags-input.min.css">
<link rel="stylesheet" href="assets/ng-tags-input.bootstrap.min.css">
</head>
<body>
<app-root></app-root>
</body>
<script src="assets/jquery.min.js"></script>
<script src="assets/materialize.min.js"></script>
<script src="assets/ng-tags-input.js"></script>
</html>
example.component.html
<div class="container" style="min-height: 70vh; min-width: 70vh; overflow:hidden;">
<div id="temp" class="row">
<div class="col s12">
<h3 style="color:#0081c7">Example Form</h3>
<hr />
<form #exampleForm="ngForm" class="col s12" (ngSubmit)="submitForm();" id="example">
<div class="row">
<div class="input-field col s8">
<input name="submissionTitle" type="text" class="validate" [(ngModel)]="model.submissionTitle" required>
<label for="submissionTitle">Submission Title</label>
</div>
</div>
<div class="row">
<div class="input-field col s4">
<tags-input ng-model="tags"></tags-input>
</div>
</div>
</form>
</div>
</div>
</div>
example.component.ts
import { Component, OnInit, ElementRef, Inject } from '#angular/core';
import { Router } from '#angular/router';
import { FormsModule, NgForm } from '#angular/forms';
import { NgModule } from '#angular/core';
import { Element } from '#angular/compiler';
import { Http, Response } from '#angular/http';
import 'rxjs/add/operator/map'
#Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
constructor(
public _http: Http,
private elementRef: ElementRef,
private router: Router
) { }
ngOnInit() {
}
submitForm() {
console.log("test");
const formElement: HTMLFormElement = this.elementRef.nativeElement.querySelector('#example');
const formData = new FormData(formElement);
this._http.post('api/submitExample', this.model).map(
(res: Response) => res.json()).subscribe(
(success) => {
alert("great");
formElement.reset();
location.reload();
},
(error) => {
alert("There was an error");
}
);
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { ExampleComponent } from './example/example.component';
import { RouterModule } from '#angular/router';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { NgTagsInput } from 'ng-tags-input';
const ROUTES = [
{
path: '',
redirectTo: 'example',
pathMatch: 'full'
},
{
path: 'example',
component: ExampleComponent
}
]
#NgModule({
declarations: [
AppComponent,
ExampleComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(ROUTES),
NgTagsInput
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I think you're mixing up Angular and AngularJS. It seems like you're using this directive, which is for AngularJS. I think this is the port of Angular 2. AngularJS and Angular 2+ are very different and their directives are not usually compatible without modification.
This means npm install ng2-tag-input --save
import { TagInputModule } from 'ng2-tag-input';
import { BrowserAnimationsModule } from '#angular/platform-
browser/animations'; // this is needed!
#NgModule({
imports: [ TagInputModule, BrowserAnimationsModule, ...OtherModules ] // along with your other modules
})
export class AppModule {}
making a test app for Angular 2 but for some reason I can't resolve, my app is stuck on "Loading..."
Here are the files:
app.component.ts:
import {Component} from '#angular/core';
import {LittleTourComponent} from './little-tour.component';
#Component({
selector: 'my-app',
template: `
<h1>Test</h1>
<little-tour></little-tour>
`,
directives: [LittleTourComponent]
})
export class AppComponent { }
little-tour.component.ts:
import {Component} from '#angular/core';
#Component ({
selector: 'little-tour',
template: `
<input #newHero (keyup.enter)='addHero(newHero.value)'
(blur)="addHero.(newHero.value); newHero.value = '' ">
<button (click) = addHero(newHero.value)>Add</button>
<ul><li *ngFor='let hero of heroes'>{{hero}}</li></ul>
`,
})
export class LittleTourComponent {
heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
addHero (value: string) {
if (value) {
this.heroes.push(value);
}
}
}
index.html:
<html>
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
and the main.ts:
import {bootstrap} from '#angular/platform-browser-dynamic';
import {AppComponent} from './app.component';
bootstrap(AppComponent);
The terminal doesn't yield any errors when I start npm but I'm sure there's something I must've missed in the code. Since I'm still trying to wrap my head around the basics of Angular 2, your help would be greatly appreciated. Thank you!
It works now with this:
<input #newHero (keyup.enter)='addHero(newHero.value)'
(blur)="addHero" newHero.value = '' >
plunker
You can add value from your input box to the list like so:
<input [(ngModel)] = "newHero">
<button (click) = addHero(newHero)>Add</button>
<ul><li *ngFor='let hero of heroes'>{{hero}}</li></ul>
I have a very simple app setup:
Index.html:
<!doctype html>
<html>
<head>
<title>Angular 2</title>
<!-- Libraries -->
<script src="/lib/js/es6-shim.js"></script>
<script src="/lib/js/angular2-polyfills.js"></script>
<script src="/lib/js/system.src.js"></script>
<script src="/lib/js/rxjs/bundles/Rx.js"></script>
<script src="/lib/js/angular2.dev.js"></script>
<!-- Stylesheet -->
<link rel="stylesheet" type="text/css" href="/app/reddit_v2/style/semantic/semantic.min.css">
<link rel="stylesheet" type="text/css" href="/app/reddit_v2/style/styles.css">
</head>
<body>
<!-- Configure System.js, our module loader -->
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('/lib/spa/app.js')
.then(null, console.error.bind(console));
</script>
<!-- Menu Bar -->
<div class="ui menu">
<div class="ui container">
<a href="#" class="header item">
header
</a>
<div class="header item borderless">
<h1 class="ui header">
Angular 2
</h1>
</div>
</div>
</div>
<div class="ui main text container">
<app></app>
</div>
</body>
</html>
app.ts
Here I'm importing post.component and it seems to work well.
import { bootstrap } from 'angular2/platform/browser';
import { Component } from 'angular2/core';
import { Post } from './components/post.component';
#Component({
selector: 'app',
templateUrl: '/app/app.html',
directives: [Post]
})
class App {
constructor() {
}
ngOnInit() {
console.log('app');
}
addArticle(title: HTMLInputElement, link: HTMLInputElement): void {
console.log(`adding title: ${title.value} and link: ${link.value}`);
}
}
bootstrap(App);
post.component.ts
import { Component } from 'angular2/core';
#Component({
selector: 'post',
template: '<p>test</p>'
//templateUrl: '/app/component/post.component.html'
})
export class Post {
constructor() {
}
ngOnInit() {
console.log('post');
}
}
All very simple, but for some reason when I run it I get:
angular2-polyfills.js:127 GET http://localhost:5000/lib/spa/components/post.component
404 error
angular2-polyfills.js:349 Error: XHR error (404 Not Found) loading http://localhost:5000/lib/spa/components/post.component(…)
Why do I get this? It seems it looks for the file http://localhost:5000/lib/spa/components/post.component
when it should apply .js to the request and get
http://localhost:5000/lib/spa/components/post.component.js'
EDIT:
Solution was:
<script>
System.config({
packages: {
'/lib/spa/': { defaultExtension: 'js' }
}
});
System.import('/lib/spa/app.js')
.then(null, console.error.bind(console));
</script>
The package loader system.js was not configured correctly..
Your configuration is wrong. You configured a package named app but your package is named lib.
Try:
<script>
System.config({
packages: {
lib: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('lib/spa/app')
.then(null, console.error.bind(console));
</script>
I've been trying to include reactjs in my project with ng-react but when I run the app throws the error "Cannot find react component LoginComponent".
the structure:
components(folder)
LoginComponent.js
controllers(folder)
login.js
directives(folder)
login.js
views(folder)
login.html
app.js
index.html:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
<link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="../bower_components/alertify.js/dist/css/alertify.css">
</head>
<body ng-app="gameApp">
<div ng-view=""></div>
<!-- COMPONENTS -->
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/react/react.js"></script>
<script src="../bower_components/react/react-dom.js"></script>
<script src="../bower_components/ngReact/ngReact.min.js"></script>
<script src="../bower_components/angular-route/angular-route.js"></script>
<script src="../bower_components/angular-resource/angular-resource.js"></script>
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="../bower_components/alertify.js/dist/js/alertify.js"></script>
<script src="../bower_components/babel/browser.js"></script>
<!-- SOCKET.IO -->
<script src="../node_modules/socket.io-client/socket.io.js"></script>
<!-- REACT COMPONENTS -->
<script type="text/babel" src="js/components/LoginComponent.js"></script>
<!-- DIRECTIVES -->
<script src="js/directives/login.js"></script>
<!-- JAVASCRIPT FILES -->
<script src="js/app.js"></script>
<!-- CONTROLLERS -->
<script src="js/controllers/login.js"></script>
<!-- SERVICES -->
<script src="js/services/commonServices.js"></script>
</body>
</html>
app.js:
'use strict';
/**
* #ngdoc overview
* #name gameApp
* #description
* # gameApp
*
* Main module of the application.
*/
angular //modules
.module('gameApp', ['ngResource',
'ngRoute',
'react',
//services
'commonServices',
//directives
'loginDirective'
])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/login', {
templateUrl: 'js/views/login.html',
controller: 'LoginController'
})
});
LoginComponent.js:
login.value('LoginComponent', React.createClass({
propTypes: {
username : React.PropTypes.string.isRequired
},
render: function() {
return <span>Hi {this.props.username}</span>;
}
}));
login.js(directive):
'use strict';
var loginDirective = angular.module('loginDirective', []);
loginDirective.directive( 'login', function( reactDirective ) {
return reactDirective( 'LoginComponent');
} );
login.html(view):
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4">
<h1 class="text-center login-title">Choose your name</h1>
<form>
<div class="form-group">
<input type="text" ng-model="username" class="form-control" placeholder="Name" autofocus>
</div>
<div class="form-group">
<button class="btn btn-lg btn-primary btn-block" ng-click="setUsername()">Enter</button>
</div>
</form>
<login username="username" />
</div>
</div>
</div>
login.js(controller):
var login = angular.module('gameApp');
login.controller('LoginController', ['$scope', '$location', 'commonServices',
function($scope, $location, commonServices) {
$scope.username = '';
$scope.setUsername = function() {
if($scope.username.trim() == '') {
alertify.error("The name can't be empty");
} else {
commonServices.setUsername($scope.username);
$location.path('/');
}
}
}
]);
Somebody knows whats the problem?
This line: return <span>Hi {this.props.username}</span>; isn't valid JavaScript because it contains JSX so it's breaking the directive. You will need to add a compile step to your workflow if you want to use JSX.
Check out my blog post to add JSX and ES6 compilation to your project http://blog.tylerbuchea.com/migrating-angular-project-to-react/
To make sure this is actually the problem try replacing your current LoginComponent code with the code below. I just took your current code and used an online compiler https://babeljs.io/repl/ So the code below should all be valid ES5 JavaScript.
Try this:
'use strict';
login.value('LoginComponent', React.createClass({
propTypes: {
username: React.PropTypes.string.isRequired
},
render: function render() {
return React.createElement(
'span',
null,
'Hi ',
this.props.username
);
}
}));
Try to compile the JSX file. For me it worked.